Network communication, now everywhere, anything does not involve the network, it feels less an arm, broken a leg, today to talk about network communication;




Paste_Image.png




Paste_Image.png

Here’s how sockets work:




Paste_Image.png

  • Based on TCP Socket programming



Paste_Image.png

Here’s an example:

Server

import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; // Server class public class Server {public static void main(String[] args) throws Exception {// Instantiates a list to save all User lists list = new ArrayList(); @suppressWarnings ("resource") ServerSocket ServerSocket = new ServerSocket(9999); System.out.println(" the server is starting ~"); While (true) {Socket Socket = serversocket.accept (); User = new User(" User "+ math.round (math.random () * 100),socket); System.out.println(user.getName() + "Login..." ); list.add(user); ServerThread thread = new ServerThread(user, list); thread.start(); }}}Copy the code

ServerThread

import java.io.IOException; import java.io.PrintWriter; import java.util.List; /* * The main functions of the server thread are: * 1. Receive information from the client * 2. * */ Public Class ServerThread extends Thread {private User User; private List list; public ServerThread(User user, List list) { this.user = user; this.list = list; } public void run() {try {while (true) { (login | | logout | | say), the sender, ShouFaRen, information body constantly read / / client sending information String MSG = user. GetBr (), readLine (); System.out.println(msg); String[] str = msg.split(","); switch (str[0]) { case "logout": remove(user); // Remove user break; case "say": sendToClient(str[1], msg); // Forward the message to a specific user break; default: break; }}} catch (Exception e) {system.out.println (" Exception "); } finally { try { user.getBr().close(); user.getSocket().close(); } catch (IOException e) { e.printStackTrace(); } } } private void sendToClient(String username, String msg) { for (User user : list) { if (user.getName().equals(username)) { try { PrintWriter pw =user.getPw(); pw.println(msg); pw.flush(); } catch (Exception e) { e.printStackTrace(); } } } } private void remove(User user2) { list.remove(user2); }}Copy the code

Client

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /* * The client thread is mainly responsible for: * 1. Sending messages * 2. Receiving messages all the time, Public class Client {public static void main(String[] args) {try {Socket Socket = new Socket("localhost", 9999); // Start a thread to receive information and parse ClientThread thread=new ClientThread(socket); thread.setName("Client1"); thread.start(); Br =new BufferedReader(new InputStreamReader(system.in)); PrintWriter out=new PrintWriter(socket.getOutputStream()); while(true) { String s=br.readLine(); out.println(s); //out.write(s+"\n"); out.flush(); }}catch(Exception e){system.out.println (" server Exception "); }}}Copy the code

ClientThread

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; Public class ClientThread extends Thread {private Socket Socket; public ClientThread(Socket socket) { this.socket = socket; } public void run() { try { InputStream inputStream = socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream); BufferedReader br = new BufferedReader(inputStreamReader); Try {/ / information format: (login | | logout | | say), the sender, ShouFaRen, information body while (true) {String MSG = br. ReadLine (); System.out.println(msg); String[] str = msg.split(","); Switch (STR [0]) {case "STR [2] +" + STR [1] + "STR [3]" + STR [3]); break; default: break; } } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e1) { e1.printStackTrace(); }}}Copy the code

User

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class User { private String name; private String account; private Socket socket; private BufferedReader br; private PrintWriter pw; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public Socket getSocket() { return socket; } public void setSocket(final Socket socket) { this.socket = socket; } public BufferedReader getBr() { return br; } public void setBr(BufferedReader br) { this.br = br; } public PrintWriter getPw() { return pw; } public void setPw(PrintWriter pw) { this.pw = pw; } public User(String name, final Socket socket) throws IOException { this.name = name; this.socket = socket; this.br = new BufferedReader(new InputStreamReader( socket.getInputStream())); this.pw = new PrintWriter(socket.getOutputStream()); } @Override public String toString() { return "User [name=" + name + ", account=" + account + ", socket=" + socket + "]"; }}Copy the code

The results of




result.gif