java利用Socket实现客户端与客户端通信


网络通信,现在随处可见,任何东西不涉及网络的话,就感觉少了条手臂,断了个腿一样,今天就来聊聊网络通信;

java利用Socket实现客户端与客户端通信_第1张图片
Paste_Image.png
java利用Socket实现客户端与客户端通信_第2张图片
Paste_Image.png

下面来看看socket的原理:

java利用Socket实现客户端与客户端通信_第3张图片
Paste_Image.png
  • 基于TCP的Socket编程
java利用Socket实现客户端与客户端通信_第4张图片
Paste_Image.png

下面来看看例子:

Server


    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    
    //服务器类
    public class Server {
    
        public static void main(String[] args) throws Exception {
    
            // 实例化一个list,用于保存所有的User
            List list = new ArrayList();
            // 创建绑定到特定端口的服务器套接字
            @SuppressWarnings("resource")
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务端正在开始~");
            // 循环监听客户端连接
            while (true) {
                Socket socket = serverSocket.accept();
                // 每接受一个线程,就随机生成一个一个新用户
                User user = new User("user" + Math.round(Math.random() * 100),socket);
    
                System.out.println(user.getName() + "正在登录。。。");
                list.add(user);
                // 创建一个新的线程,接收信息并转发
                ServerThread thread = new ServerThread(user, list);
                thread.start();
            }
        }
    }

ServerThread


    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    
    /*
     *   服务器线程的作用主要是:
     *   1.接收来自客户端的信息
     *   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),发送人,收发人,信息体
                    //不断地读取客户端发过来的信息
                    String msg= user.getBr().readLine();
                    System.out.println(msg);
                    String[] str = msg.split(",");
                    switch (str[0]) {
                        case "logout":
                            remove(user);// 移除用户
                            break;
                        case "say":
                            sendToClient(str[1], msg); // 转发信息给特定的用户
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                System.out.println("异常");
            } 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);
        }
    }

Client


    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    
    /*
     *   client线程主要是负责:
     *   1.发送信息
     *   2.一直接收信息,并解析
     * */
    public class Client {
    
        public static void main(String[] args) {
            try {
                Socket socket = new Socket("localhost", 9999);
                //开启一个线程接收信息,并解析
                ClientThread thread=new ClientThread(socket);
                thread.setName("Client1");
                thread.start();
                //主线程用来发送信息
                BufferedReader 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("服务器异常");
            }
        }
    }

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 {
                    // 信息的格式:(login||logout||say),发送人,收发人,信息体
                    while (true) {
                        String msg=br.readLine();
                        System.out.println(msg);
                        String[] str = msg.split(",");
                        switch (str[0]) {
                            case "say":
                                System.out.println(str[2] + " 对   " + str[1] + " say:  "
                                        + str[3]);
                                break;
                            default:
                                break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

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 + "]";
        }
    }

结果

result.gif

你可能感兴趣的:(java利用Socket实现客户端与客户端通信)