Home>Article>Java> JAVA Advanced Learning Socket Programming

JAVA Advanced Learning Socket Programming

WBOY
WBOY forward
2022-11-16 16:17:11 2190browse

This article brings you relevant knowledge aboutjava, which mainly introduces the relevant content about socket programming. Socket is an interface or an interface provided by the network driver layer to the application. Let’s take a look at the mechanism below. I hope it will be helpful to everyone.

JAVA Advanced Learning Socket Programming

Recommended study: "java video tutorial"

1. Socket knowledge

1. Socket Overview

(1) Java originally appeared as a network programming language. Its high support for the network makes smooth communication between the client and the server a reality.

(2) In network programming, Socket is the most used, and its participation is indispensable in every practical network program.

(3) In computer network programming technology, two processes or two computers can exchange data through a network communication connection. The endpoint of this communication link is called a "socket" ” (The English name is Socket).

(4) Socket is an interface or mechanism provided by the network driver layer to the application.

(5) Use the example of logistics to deliver express delivery to illustrate Socket:

-->The sender will deliver the goods with the consignee's address information to the express station, and the sender does not need to Pay attention to how the logistics is carried out. The goods are sent to the express delivery station in the consignee's area for delivery, and the consignee just waits to receive the goods.

--> This process vividly illustrates the process of information transmission in the network. Among them, the goods are data information, and the two express delivery sites are the two endpoint Sockets.

# (6) The application does not need to care about how information is addressed and transmitted in the network. It is only responsible for preparing to send data and receive data.

2. Socket Communication Principle

(1) For programmers, there is no need to understand how the underlying mechanism of Socket transmits data. Instead, the data is submitted directly to Socket, and Socket will respond according to the application. The relevant information provided by the program is bound to the IP and information data through a series of calculations, and the data is handed over to the driver to be sent to the network.

(2) The underlying mechanism of Socket is very complex. The Java platform provides some simple but powerful classes that can simply and effectively use Socket to develop communication programs without knowing the underlying mechanism.

3. java.net package

(1) The java.net package provides several classes that support socket-based client/server communication.

(2) Commonly used classes in the java.net package include Socket, ServerSocket, DatagramPacket, DatagramSocket, InetAddress, URL, URLConnection and URLEncoder, etc.

(3) In order to monitor the client’s connection request, you can use the ServerSocket class.

(4) The Socket class implements a socket for inter-process communication on the network.

(5) The DatagramSocket class uses the UDP protocol to implement client and server sockets.

(6) The DatagramPacket class uses the object of the DatagramSocket class to encapsulate settings and received datagrams.

(7) The InetAddress class represents the Internet address.

(8) When creating datagram messages and Socket objects, you can use the InetAddress class

2. Socket programming based on TCP protocol

1.Socket Class and ServerSocket class

(1) The two classes Socket and ServerSocket of the java.net package are used to implement the client and server side of two-way secure connections respectively. They are based on the TCP protocol When working, the working process is like making a phone call. Only when both parties are connected can the call start.

(2) During network communication, Socket needs to use data flow to complete the data transfer.

(3) If an application wants to send data to another application over the network, it simply creates a Socket and then writes the data to the output stream associated with the Socket. Correspondingly, the receiving application creates a Socket and reads data from the associated input stream.

(4) Note: In Socket programming based on the TCP protocol, the two endpoints often serve as the client and the other as the server, that is, following the client-server model.

● Socket class

The Socket object establishes a connection between the client and the server. You can use the constructor method of the Socket class to create a socket and connect this socket to the specified host and port.

(1) Construction method

   —>The first construction method takes the host name and port number as parameters to create a Socket object. UnknownHostException or IOException may be thrown when creating an object, and they must be caught.

Socket s = new Socket(hostName,port);

--> The second construction method takes the InetAddress object and the port number as parameters to create a Socket object. The constructor may throw IOException or UnknownHostException, which must be caught and handled.

Socket s = new Socket(address,port);

(2) Common methods

● ServerSocket class

The ServerSocket object waits for the client to establish a connection and communicates after the connection is established.

(1)Construction method

-->The first construction method accepts the port number as a parameter to create a ServerSocket object. When creating this object, an IOException may be thrown, and it must be captured and processed. .

Serversocket SS = New Serversocket (Port);

##-& GT; The second constructor accepts the length and maximum queue length as the parameter. The maximum number of client connections that can be had before the connection is rejected.

using ss using using using ss through ss through to ss = new ss = new ServerSocket(port, maxqu);

Methods also apply to the ServerSocket class.

    —>The ServerSocket class has an accept() method, which is used to wait for the client to initiate communication so that the Socket object can be used for further data transmission.

2. Use Socket programming to implement the login function


##● To achieve single-user login

 — ->Socket network programming is generally divided into the following four steps:

(1) Establish a connection.

(2) Open the input/output stream associated with the Socket.

(3) Write information and read information from the data stream.

(4) Close all data streams and Sockets.

-& GT; Use two classes to simulate the function of user login to realize the client sent the user login information to the server side, and display the information on the server side.

Client implementation steps:

1) Establish a connection, and the connection points to the server and port.

2) Open the input/output stream associated with the Socket.

3) Write information to the output stream.

4) Read the response information from the input stream.

5) Close all data streams and Sockets.

Server-side implementation steps:

1) Establish a connection and listen to the port.

2) Use the accept() method to wait for the client to initiate communication

3) Open the input/output stream associated with the Socket.

4) Read the request information from the input stream.

5) Write information to the output stream.

6) Close all data streams and Sockets.

#-& gt; The client and server interaction, adopt a mode of answering, first start the server to enter the monitoring state, wait for the client's connection request. After the connection is successful, the client first speaks. ", the server gives "response".

Example 01: Implement the transfer of object information.

♥ user class

package cn.bdqn.demo02; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; /** 用户名 */ private String loginName; /** 用户密码 */ private String pwd; public User() { super(); } public User(String loginName, String pwd) { super(); this.loginName = loginName; this.pwd = pwd; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }

♥ LoginServer class

package cn.bdqn.demo02; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class LoginServer { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; try { // 建立一个服务器Socket(ServerSocket),指定端口8800并开始监听 serverSocket = new ServerSocket(8800); // 使用accept()方法等待客户端发起通信 socket = serverSocket.accept(); // 打开输入流 is = socket.getInputStream(); // 反序列化 ois = new ObjectInputStream(is); // 获取客户端信息,即从输入流读取信息 User user = (User) ois.readObject(); if (user != null) { System.out.println("我是服务器,客户登录信息为:" + user.getLoginName() + "," + user.getPwd()); } // 给客户端一个响应,即向输出流中写入信息 String reply = "欢迎你,登录成功"; os = socket.getOutputStream(); os.write(reply.getBytes()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { // 关闭资源 try { os.close(); ois.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

LoginClient class

package cn.bdqn.demo02; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class LoginClient { /* * 示例02:升级演示示例01,实现传递对象信息。 */ public static void main(String[] args) { Socket socket = null; OutputStream os = null; ObjectOutputStream oos = null; InputStream is = null; BufferedReader br = null; try { // 建立客户端Socket连接,指定服务器的位置为本机以及端口为8800 socket = new Socket("localhost", 8800); // 打开输出流 os = socket.getOutputStream(); // 对象序列化 oos = new ObjectOutputStream(os); // 发送客户端信息,即向输出流中写入信息 User user = new User("Tom", "123456"); oos.writeObject(user); socket.shutdownOutput(); // 接收服务器端的响应,即从输入流中读取信息 is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String reply; while ((reply = br.readLine()) != null) { System.out.println("我是客户端,服务器的响应为:" + reply); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); is.close(); oos.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

Example 02: Upgraded demonstration example 01 to realize the transmission of multiple object information.

user class

package cn.bdqn.demo03; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; /** 用户名 */ private String loginName; /** 用户密码 */ private String pwd; public User() { super(); } public User(String loginName, String pwd) { super(); this.loginName = loginName; this.pwd = pwd; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }

LoginServer class

package cn.bdqn.demo03; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class LoginServer { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; try { // 建立一个服务器Socket(ServerSocket),指定端口8800并开始监听 serverSocket = new ServerSocket(8800); // 使用accept()方法等待客户端发起通信 socket = serverSocket.accept(); // 打开输入流 is = socket.getInputStream(); // 反序列化 ois = new ObjectInputStream(is); // 获取客户端信息,即从输入流读取信息 User[] users = (User[]) ois.readObject(); for (int i = 0; i < users.length; i++) { System.out.println("我是服务器,客户登录信息为:" + users[i].getLoginName() + "," + users[i].getPwd()); } // 给客户端一个响应,即向输出流中写入信息 String reply = "欢迎你,登录成功"; os = socket.getOutputStream(); os.write(reply.getBytes()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { // 关闭资源 try { os.close(); ois.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

LoginClient class

package cn.bdqn.demo03; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class LoginClient { /* * 示例02:升级演示示例01,实现传递对象信息。 */ public static void main(String[] args) { Socket socket = null; OutputStream os = null; ObjectOutputStream oos = null; InputStream is = null; BufferedReader br = null; try { // 建立客户端Socket连接,指定服务器的位置为本机以及端口为8800 socket = new Socket("localhost", 8800); // 打开输出流 os = socket.getOutputStream(); // 对象序列化 oos = new ObjectOutputStream(os); // 发送客户端信息,即向输出流中写入信息 User user1 = new User("Tom", "123456"); User user2 = new User("bob", "123456"); User user3 = new User("lisa", "123456"); User[] users = {user1,user2,user3}; oos.writeObject(users); socket.shutdownOutput(); // 接收服务器端的响应,即从输入流中读取信息 is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String reply; while ((reply = br.readLine()) != null) { System.out.println("我是客户端,服务器的响应为:" + reply); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); is.close(); oos.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

● Implement multiple clients User login

## -->The one-question-one-answer model is obviously not what people want in reality. A server cannot only serve one client, but generally provides services to many clients at the same time. However, single-threaded implementation must be the result.

    —>The solution to this problem is to use multi-threading. You can create an application main service program on the server side that is specifically responsible for monitoring, and a thread program that is specifically responsible for responding. This enables multi-threading to handle multiple requests.

Client side implementation steps:

1) Establish a connection, and the connection points to the server and port.

2) Open the input/output stream associated with the Socket.

3) Write information to the output stream.

4) Read the response information from the input stream.

5) Close all data streams and Sockets.

#-& GT; Server end implementation steps:

1) Create the server thread class, and the response processing of a request in the RUN () method.

2) Modify the server-side code so that the server-side Socket is always in a listening state.

3) Every time the server monitors a request, it creates a thread object and starts it.

Example 03: Upgrade demonstration example 02 to implement response processing for multiple clients.

user class

package cn.bdqn.demo04; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; /** 用户名 */ private String loginName; /** 用户密码 */ private String pwd; public User() { super(); } public User(String loginName, String pwd) { super(); this.loginName = loginName; this.pwd = pwd; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
LoginThread

package cn.bdqn.demo04; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.Socket; public class LoginThread extends Thread { /* * 示例03:升级示例02,实现多客户端的响应处理。 * * 分析如下: * (1)创建服务器端线程类,run()方法中实现对一个请求的响应处理。 * (2)修改服务器端代码,让服务器端Socket一直处于监听状态。 * (3)服务器端每监听到一个请求,创建一个线程对象并启动 */ Socket socket = null; //每启动一个线程,连接对应的Socket public LoginThread(Socket socket) { this.socket = socket; } //启动线程,即响应客户请求 public void run() { InputStream is = null; ObjectInputStream ois = null; OutputStream os = null; try { //打开输入流 is = socket.getInputStream(); //反序列化 ois = new ObjectInputStream(is); //获取客户端信息,即从输入流读取信息 User user = (User)ois.readObject(); if(user!=null){ System.out.println("我是服务器,客户登录信息为:"+user.getLoginName()+","+user.getPwd()); } //给客户端一个响应,即向输出流中写入信息 os = socket.getOutputStream(); String reply = "欢迎你,登录成功"; os.write(reply.getBytes()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ try { os.close(); ois.close(); is.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
LoginServer class

package cn.bdqn.demo04; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class LoginServer { public static void main(String[] args) { ServerSocket serverSocket = null; try { // 建立一个服务器Socket(ServerSocket)指定端口并开始监听 serverSocket = new ServerSocket(8800); // 监听一直进行中 while (true) { // 使用accept()方法等待客户发起通信 Socket socket = serverSocket.accept(); LoginThread loginThread = new LoginThread(socket); loginThread.start(); } } catch (IOException e) { e.printStackTrace(); } } }
♥ LoginClient1 class

package cn.bdqn.demo04; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class LoginClient01 { /* * 客户端通过输出流向服务器端发送请求信息 * 服务器侦听客户端的请求得到一个Socket对象,将这个Socket对象传递给线程类 * 线程类通过输入流获取客户端的请求并通过输出流向客户端发送响应信息 * 客户端通过输入流读取服务器发送的响应信息 * */ /* * 示例03:升级演示示例02,实现多客户端的响应处理 */ public static void main(String[] args) { Socket socket = null; OutputStream os = null; ObjectOutputStream oos = null; InputStream is = null; BufferedReader br = null; try { // 建立客户端Socket连接,指定服务器的位置为本机以及端口为8800 socket = new Socket("localhost", 8800); // 打开输出流 os = socket.getOutputStream(); // 对象序列化 oos = new ObjectOutputStream(os); // 发送客户端信息,即向输出流中写入信息 User user = new User("Tom", "123456"); oos.writeObject(user); socket.shutdownOutput(); // 接收服务器端的响应,即从输入流中读取信息 is = socket.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String reply; while ((reply = br.readLine()) != null) { System.out.println("我是客户端,服务器的响应为:" + reply); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); is.close(); oos.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
♥ LoginClient2 Class and LoginClient3 class

Like the LoginClient1 class, just create different User objects

-->The InetAddress class in the java.net package is used to encapsulate IP addresses and DNS . To create an instance of the InetAddress class, you can use the factory method since this class has no constructor.

-& GT; The factory method in the INetaddress class

-& GT; If you can't find the host, both methods will be thrown out of unknownhostnameexception abnormalities.

3. Socket programming based on UDP protocol

1.DatagramPacket class and DatagramSocket class

(1) TCP-based network communication is secure and bidirectional. Just like making a phone call, a server is required first. After establishing a bidirectional connection, Just start data communication.

(2) UDP-based network communication only requires specifying the other party's address and then sending the data, without prior connection. Such network communication is unsafe, so it is only used in situations such as chat systems and consultation systems.

(3) Datagram is a type of message that represents communication. When using datagram for communication, there is no need to establish a connection in advance. It is based on the UDP protocol.

(4) There are two classes in Java that can use datagrams to achieve communication, namelyDatagramPacketandDatagramSocket.

(5) The DatagramPacket class plays the role of a container, and the DatagramSocket class is used to send or receive DatagramPacket.

(6)DatagramPacket class does not provide methods to send or receive data, while DatagramSocket class providessend()method andreceive()method, use For sending and receiving datagrams over sockets.

##● DatagramPacket class

(1) Construction method

-->The DatagramSocket class does not maintain the connection status and does not generate input/output data streams. Its only function is to receive and send datagrams encapsulated by the DatagramPacket object.

(2) Common methods

2. Use Socket programming to implement customer consultation

->The two endpoints communicating using UDP are equal, which means that the relationship between the two communication programs is equal, there is no priority, and even their codes can be exactly the same. This is different from that based on Socket programming of TCP protocol is distinguished.

Socket network programming based on UDP protocol generally follows the following 4 steps:

.

(2) Use the DatagramSocket object to send data packets.

(3) Use the DatagramSocket object to receive data packets.

(4) Use the DatagramPacket object to process data packets.

Sender implementation steps:

1) Obtain the InetAddress object of the local host.

2) Create a DatagramPacket object to encapsulate the information to be sent.

3) Use the DatagramSocket object to send the DatagramPacket object data.

1) Create a DatagramPacket object and prepare to receive the encapsulated data.

2)创建DatagramSocket对象,接收数据保存于DatagramPacket对象中。

3)利用DatagramPacket对象处理数据。

示例04:发送方发送咨询问题,接收方回应咨询。

♥ Receive类

package cn.bdqn.demo05; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketAddress; import java.net.SocketException; public class Receive { public static void main(String[] args) { /* * 示例06:发送方发送咨询问题,接收方回应咨询。 * * 接收方实现步骤如下: * (1)创建DatagramPacket对象,准备接收封装的数据。 * (2)创建DatagramSocket对象,接收数据保存于DatagramPacket对象中。 * (3)利用DatagramPacket对象处理数据。 */ DatagramSocket ds = null; DatagramPacket dp = null; DatagramPacket dpto = null; // 创建DatagramPacket对象,用来准备接收数据 byte[] buf = new byte[1024]; dp = new DatagramPacket(buf, 1024); try { // 创建DatagramSocket对象,接收数据 ds = new DatagramSocket(8800); ds.receive(dp); // 显示接收到的信息 String mess = new String(dp.getData(), 0, dp.getLength()); System.out.println(dp.getAddress().getHostAddress() + "说:" + mess); String reply = "你好,我在,请咨询!"; // 显示与本地对话框 System.out.println("我 说:" + reply); // 创建DatagramPacket对象,封装数据 SocketAddress sa = dp.getSocketAddress(); dpto = new DatagramPacket(reply.getBytes(), reply.getBytes().length, sa); ds.send(dpto); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { ds.close(); } } }

♥ Send类

package cn.bdqn.demo05; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class Send { /* * 示例06:升级示例05,发送方发送咨询问题,接收方回应咨询。 * * 发送方实现步骤如下: * (1)获取本地主机的InetAddress对象。 * (2)创建DatagramPacket对象,封装要发送的信息。 * (3)利用DatagramSocket对象将DatagramPacket对象数据发送出去。 */ public static void main(String[] args) { DatagramSocket ds = null; InetAddress ia = null; String mess = "你好,我想咨询一个问题。"; System.out.println("我说:" + mess); try { // 获取本地主机地址 ia = InetAddress.getByName("localhost"); // 创建DatagramPacket对象,封装数据 DatagramPacket dp = new DatagramPacket(mess.getBytes(), mess.getBytes().length, ia, 8800); // 创建DatagramSocket对象,向服务器发送数据 ds = new DatagramSocket(); ds.send(dp); byte[] buf = new byte[1024]; DatagramPacket dpre = new DatagramPacket(buf, buf.length); ds.receive(dpre); // 显示接收到的信息 String reply = new String(dpre.getData(), 0, dpre.getLength()); System.out.println(dpre.getAddress().getHostAddress() + "说:" + reply); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { ds.close(); } } }

推荐学习:《java视频教程

Whether to connect Connection-oriented Non-connection-oriented Transmission reliability Reliable Unreliable Speed (1)Construction method-->The client wants to send data out. You must first create a DatagramPacket object and then use the DatagramSocket object to send it.(2) Common methods##● DatagramSocket class##     —>Simulate the customer consultation function, allowing the sender to send consultation questions, and the receiver to receive and display the sent consultation questions.Receiver implementation steps:

##TCP
UDP
##Slow Fast

The above is the detailed content of JAVA Advanced Learning Socket Programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete