欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Socket实现多客户端

程序员文章站 2022-05-18 14:50:33
...

Java Socket实现多客户端

实现类

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author wenhui
 * @description
 * @Date 2019/12/22
 */
public class ReadAndWriteClient implements Runnable {

    private Thread read;
    private Thread write;

    private DataInputStream dis;
    private DataOutputStream dos;
    private PrintWriter pr;
    private boolean isConnected;
    private Socket socket;

    public ReadAndWriteClient(Socket socket) {
        Objects.requireNonNull(socket);
        try {
            this.socket = socket;
            dis = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
            isConnected = true;
        } catch (IOException e) {
            disconnect();
            System.err.println("初始化失败,聊天退出...");
        }
    }

    @Override
    public void run() {
        read = new Thread(this::read);
        write = new Thread(this::write);
        read.start();
        write.start();
    }

    private void read() {
        try {
            while (isConnected) {
                isServerClose(socket);
                byte[] data = new byte[1024];
                dis.read(data);
                System.out.println(socket.getInetAddress()+":"+socket.getPort()+ Arrays.toString(data));
            }
        } catch (IOException e) {
            if (isConnected) {
                System.err.println("读取数据失败,断开连接...");
                disconnect();
            }
        }
    }

    private void write() {
        try {
            System.out.println("请输入数据 : ");
            while (isConnected) {
                Scanner scanner = new Scanner(System.in);
                String line = scanner.nextLine();
                if ("0".equals(line)) {
                    System.out.println("你选择了结束通信...");
                    break;
                }
                pr = new PrintWriter(dos);
                pr.write(line);
                pr.flush();
                dos.flush();
            }
            disconnect();
        } catch (IOException e) {
            System.err.println("程序出错了,断开连接...");
            disconnect();
        }
    }

    private void disconnect() {
        try {
            if (dis != null)
                dis.close();
            if (pr != null)
                pr.close();
            if (dos != null)
                dos.close();
            if (socket != null)
                socket.close();

            isConnected = false;
        } catch (IOException e) {
            System.err.println("连接断开异常...");
        }
    }

    public Boolean isServerClose(Socket socket){
        try{
            socket.sendUrgentData(0xFF);//发送1个字节的紧急数据,默认情况下,服务器端没有开启紧急数据处理,不影响正常通信
            return false;
        }catch(Exception se){
            return true;
        }
    }
}

测试类

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wenhui
 * @description
 * @Date 2019/12/22
 */
public class RWClientStart {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 保存已有的连接
        List<Socket> sockets = new ArrayList<>();
        Socket socket1 = new Socket("localhost", 8080);
        Socket socket2 = new Socket("localhost", 8081);
        new Thread(new ReadAndWriteClient(socket1)).start();
        new Thread(new ReadAndWriteClient(socket2)).start();
        sockets.add(socket1);
        sockets.add(socket2);
        Thread.sleep(3000);
        for(Socket socket: sockets) {
            System.out.println("已连接:"+socket.getInetAddress()+":"+socket.getPort());
        }
    }
}

输出:
Java Socket实现多客户端
Java Socket实现多客户端

相关标签: Java