阅读背景:

java网络编程-TCP-多人群聊(自问自答)

来源:互联网 

在线聊天室
服务器:

public class Chat {

public static void main(String[]args) throws IOException
{
    System.out.println("服务器启动中...");
    //创立服务器
    ServerSocket server=new ServerSocket(9999);
    //阻塞式期待衔接,当客户端Socket创立好以后才开启

    while(true)
    {
    Socket client=server.accept();
    System.out.println("一个客户端树立了衔接");

    new Thread(()->{
        DataInputStream dis = null;
        DataOutputStream dos = null;
        try {
            dis = new DataInputStream(client.getInputStream());
            dos = new DataOutputStream(client.getOutputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        boolean flag=true;
        while(flag) {

        String msg = null;
        try {
            msg = dis.readUTF();
            dos.writeUTF(msg);
            dos.flush();
        } catch (IOException e) {

            //当断掉客户端衔接时,不用重复再读取数据
            flag=false;
        }

        //返回资讯

        }
        try {
            if(null!=dos)
            {
            dos.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
        try {
            if(null!=dis)
            {
            dis.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
        try {
            if(null!=client)
            {
            client.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }).start();

    }
    }

}public class Chat {

public static voi



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: