java-socket多线程通信(二)

SocketThread

Socket多线程处理类
/**
 * Socket多线程处理类
 */
public class SocketThread extends Thread {
    private Socket socket;

    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //获得输入输出流
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter os = new PrintWriter(socket.getOutputStream());

            System.out.println("接收到客户端信息:" + is.readLine());

            os.write("你好客户端!");
            os.flush();
            socket.shutdownOutput();// 关闭输出流

            //关闭相对应的资源
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ManyThreadSocketServer

public class ManyThreadSocketServer {

    /**
     * Socket服务端
     */
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务端启动!等待连接");

            while (true) {
                Socket socket = serverSocket.accept();
                SocketThread socketThread = new SocketThread(socket);
                socketThread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client和上一篇差不多

你可能感兴趣的:(java基础)