Java Network Programming

I. Construct IP address:

InetAddress ip = InetAddress.getByName(host); //host can be a computer name or an IP address such as 127.0.0.1Copy the code

Socket Socket

In the program to use a scoket communication, socket communication needs to specify IP, port, protocol (UDP, TCP); Data transmission is divided into two steps: 1. The first step is to listen (waiting for data to be sent), which is used to receive data. 2, the second part is to send (need to specify which computer to send: IP address, which program of the computer: Port number).

Sockets are divided into sender and receiver: The sender is usually a client, and the receiver is usually a server.

Generally, there are multiple clients and one server.

Use UDP protocol

UDP directly sends datagrams to the receiving end without establishing a connection, regardless of whether the receiving end receives the datagrams. So using UDP protocol for network data transmission is not reliable, but fast!

Using DatagramSocket to send data:

DatagramSocket ds = new DatagramSocket(); / / socket socketCopy the code

Use DatagramPacket as a package:

byte[] buf = "Hello, I want to send you data!".getBytes(); // array of bytes int length = buf.length; InetAddress = inetaddress.getByName ("127.0.0.1"); Int port = 7878; DatagramPacket dp = new DatagramPacket(buf, Length, address, port); // Package to be deliveredCopy the code

Send () Sends data, and close() releases resources.

ds.send(dp); //ds.send(dp); // Send 2 times... //ds.send(dp); Ds.close (); // Release resourcesCopy the code

For example 🌰 :

//UDP sender public class Demo2_UDP_Send {public static void main(String[] args) throws Exception {DatagramSocket ds = new  DatagramSocket(); //socket Socket byte[] buf ="Hello, I want to send you data!".getBytes(); // array of bytes int length = buf.length; InetAddress = inetaddress.getByName ("127.0.0.1"); Int port = 7878; DatagramPacket dp = new DatagramPacket(buf, length, address, port); Ds.send (dp); / / send ds. The close (); // Release resources}}Copy the code

Using UDP protocol to develop the receiver: using DatagramSocket to listen to the data sent from the sender:

DatagramSocket ds = new DatagramSocket(7878); // The listener port on the receiving endCopy the code

Use DatagramPacket as the container to receive data:

byte[] buf = new byte[1024]; int length = buf.length; DatagramPacket dp = new DatagramPacket(buf, length); // Directly as a container to receive dataCopy the code

Receive () Receives data, and the application waits for it to arrive:

ds.receive(dp); // Wait for data to arriveCopy the code

The same as the sender, after receiving data, also need to release the object DS resources:

ds.close(); // Data is received and resources are releasedCopy the code

For example 🌰 :

//UDP receiver public class Demo3_UDP_Receive {public static void main(String[] args) throws Exception {DatagramSocket ds = new DatagramSocket(7878); Byte [] buf = new byte[1024]; int length = buf.length; DatagramPacket dp = new DatagramPacket(buf, length); Ds.receive (dp); String STR = new String(dp.getData(), 0, dp.getLength()); System.out.println(str); Ds.close (); // Receive data, release resources}}Copy the code

Program running results:

Other information at the receiving end:

dp.getAddress(); // Get the IP address of the sender dp.getPort(); // Get the port number of the senderCopy the code

Using UDP protocol to achieve two-way chat between two users:

Create a new class called SendThread:

public class SendThread extends Thread {
	
	private int port;
	public SendThread(int port) {
		this.port=port;
	}
	
	@Override
	public void run() { DatagramSocket ds=null; try { ds = new DatagramSocket(); Scanner inputstr = new Scanner(System.in); // Enter datawhile (true) {
				String str = inputstr.nextLine();
				if (str.equals("end")) break; byte[] buf = str.getBytes(); // array of bytes int length = buf.length; InetAddress = inetaddress.getByName ("127.0.0.1"); // Specify the receiver IP address //int port = 7878; DatagramPacket dp = new DatagramPacket(buf, length, address, port); Ds.send (dp); }} catch (Exception e) {// TODO auto-generated catch block e.printStackTrace(); } finally {if(ds! Ds.close (); =null) {ds.close(); }}}}Copy the code

Create a ReceiveThread class.

public class ReceiveThread extends Thread {
	
	private int port;
	public ReceiveThread(int port) {
		this.port=port;
	}
	
	@Override
	public void run() { DatagramSocket ds=null; try { ds = new DatagramSocket(port); // Specify a port number to listen for data, corresponding to the port on which the sender sends packetswhile (true) { byte[] buf = new byte[1024]; int length = buf.length; DatagramPacket dp = new DatagramPacket(buf, length); Ds.receive (dp); String STR = new String(dp.getData(), 0, dp.getLength()); System.out.println("Received from port"+dp.getPort()+"The news :"+str); }} catch (Exception e) {// TODO auto-generated catch block e.printStackTrace(); } finally {if(ds! Ds.close (); =null) {ds.close(); }}}}Copy the code

Create class Chant_User01 (user1);

public class Chant_User01 { public static void main(String[] args) { new SendThread(7878).start(); // The sending thread of user 1. Port 7878 is the listening port of the receiving thread of user 2. New ReceiveThread(7879).start(); // User 1's receiving thread, 7879 listens for data sent from user 2}}Copy the code

Create class Chant_User02 (user2);

public class Chant_User02 { public static void main(String[] args) { new ReceiveThread(7878).start(); // User 2's receiving thread, 7878 listens for data sent from user 1 new SendThread(7879).start(); // User 2's sending thread, 7879 is user 1's receiving thread listening port}}Copy the code

Effect:

Customer 1:

Customer 2:

4. Use TCP

The TCP protocol requires a three-way handshake to establish a connection. The client and server are connected through a two-way channel. They can send or receive data using the output stream. So the use of TCP protocol network data transmission is reliable, but the speed is slow!

Using TCP to develop the client: The client directly uses sockets and uses OutputStream to write data and send it:

Socket s = new Socket("127.0.0.1", 8888); OutputStream output = s.getOutputStream(); output.write("ww.baidu.com".getBytes()); // Write data to the server. Close ();Copy the code

Using TCP protocol to develop the server: The server uses ServerSocket, accept() to wait to receive the TCP connection request sent by the client. After successfully creating a connection with the client, a socket object will be returned. The socket object can create an InputStream InputStream to receive data sent by the client. You can also create an OutputStream to send data.

ServerSocket ss = new ServerSocket(8888); Socket client = ss.accept(); InputStream Input = client.getinputStream (); InputStream input = client.getinputStream (); // Use the input stream to receive data byte[] buf = new byte[1024]; int length = input.read(buf); // Wait for the client to send data client.close(); // Close connection ss.close();Copy the code

Using TCP to implement the two-way chat function at both ends:

Create TCP_Client client class:

Public class TCP_Client {public static void main(String[] args) throws Exception {Socket s = new Socket("127.0.0.1", 8888); OutputStream output = s.getoutputStream (); InputStream input = s.getinputStream (); // Use input stream to receive data from Server /** * Anonymous inner class creates a thread to receive data ** / newThread() {
			public void run() { byte[] buf = new byte[1024]; Int length = -1; try {while((length = input.read(buf))! System.out.println(new String(buf, 0, length)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); /** */ Scanner Scanner = new Scanner(system.in);while (true) {
			String in_str = scanner.nextLine();
			if (in_str.equals("end"))break; output.write(in_str.getBytes()); // Write data to the Server} s.close(); // Close the connection}}Copy the code

Create TCP_Server server class

//TCP connection server public class TCP_Server {public static void main(String[] args) throws Exception {ServerSocket SS = new ServerSocket(8888); Socket client = ss.accept(); System.out.println(system.out.println ("Client connected in!"); InputStream input = client.getInputStream(); OutputStream output = client.getOutputStream(); // Use the output stream to send data /** * Anonymous inner class creates a thread to send data ** / newThread() {
			public void run() {
				Scanner scanner = new Scanner(System.in);
				while (true) {
					String str = scanner.nextLine();
					if (str.equals("end"))break; try { output.write(str.getBytes()); } catch (IOException e) {// TODO auto-generated catch block e.printStackTrace(); // TODO auto-generated catch block e.printStackTrace(); } } } }.start(); /** * Receive data ** / byte[] buf = new byte[1024]; int length = -1;while((length = input.read(buf))! System.out.println(new String(buf, 0, length)); } client.close(); // Close the connection to the client ss.close(); // Close listener}}Copy the code

Running results:

Client:

Server:

Multiple clients send data, and one server receives data:

1. Create TCP_Server_Many class, which can receive TCP server connected by multiple clients and process data from multiple clients:

public class TCP_Server_Many { public static void main(String[] args) { new VerbClientConnect().start(); Class VerbClientConnect extends Thread {@override public void Class VerbClientConnect extends Thread {@override public void class VerbClientConnect extends Thread {@override public voidrun() {
		try {
			ServerSocket serverSocket = new ServerSocket(8888);
			int i=0; 
			while (true) { Socket socket = serverSocket.accept(); // wait for the request to connect. System.out.println("Received a Client connection: Client"+i+socket.getInetAddress()); new ClientMessage(socket,i).start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Class ClientMessage extends Thread {private Socket Socket; private int i; public ClientMessage(Socket socket, int i) { this.socket=socket; this.i=i; } @Override public voidrun() { try { InputStream input = socket.getInputStream(); // Use the input stream to receive data byte[] buf = new byte[1024]; int length = -1;while((length = input.read(buf))! = 1) {// Wait for the client to send data system.out.println ("From Client Client"+i+"The news:"+new String(buf, 0, length));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(socket! =null) { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }Copy the code

Create TCP_Client_Many TCP client that can send multiple packets:

public class TCP_Client_Many {
	public static void main(String[] args) throws Exception {
		Socket socket = new Socket("127.0.0.1", 8888); OutputStream output = socket.getOutputStream(); // Use the output stream to send data Scanner Scanner = new Scanner(system.in);while (true) {
			String str = scanner.nextLine();
			if (str.equals("end"))break; output.write(str.getBytes()); // Send data to the server} socket.close(); }}Copy the code

Operation effect:

Client1:

Client2:

Client3:

Server:

Today’s Message:

The best time to plant a tree was ten years ago, followed by now!

Welcome to pay attention to personal wechat public account: Tao Li Bao Chun