This article brings you relevant knowledge about java, 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.
Recommended study: "java video tutorial"
(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.
(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.
(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
(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(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-->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 protocolpackage 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; } }LoginThreadpackage 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 classpackage 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 classpackage 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
##TCP |
UDP | |
Connection-oriented | Non-connection-oriented | |
Reliable | Unreliable | |
##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!