Java, imitation QQ, socket, TCP connection to make an instant messaging software
import java.io.DataInputStream;// Import the DataInputStream class
import java.io.DataOutputStream;/ / import DataOutputStream
import java.io.IOException;// Import the IOException class
import java.net.Socket;// Import the Socket class
import java.util.Scanner;// Import the Scanner class
Copy the code
First we need to import these classes
Client: 1 Determine the IP address and communication port
private String host = "127.0.0.1";// Connect to the local machine by default
private int port = 8090;// Connects to port 8090 by default
Copy the code
2 create a socket
Socket socket = new Socket(host, port);// Create a Socket object
Copy the code
3 Information Reading and Writing
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Copy the code
Server 1 Create a server socket
ServerSocket server = new ServerSocket(port);// Create ServerSocket class
Copy the code
2 Wait for the client to connect
Socket socket = server.accept();
Copy the code
3 Transfer information with the client
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Copy the code
Finally, the code runs directly to get the desired communication. The main point here is: the server needs to be turned on first, otherwise the client will fail to connect.
Running results:
Here the server and client can talk to each other. The realization principle of QQ is that multiple clients connect to the server, and then transfer information through the server for dialogue.
Complete code, please move to the public number: poetic code! [insert picture description here] (HTTP: / / https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/564109685d2c4dc182a0658e8df16296~tplv-k3u1fbpfcp-zoom-1.im age)Copy the code