JAvaネットワークプログラミング-TCP-マルチチャット(自問自答)

2313 ワード

オンラインチャットルームサーバ:
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 Client {
public static void main(String[]args) throws UnknownHostException, IOException
{
    System.out.println("      ...");

    Socket client=new Socket("localhost",9999);
    //       
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    DataOutputStream dos=new DataOutputStream(client.getOutputStream());
    DataInputStream dis =new DataInputStream(client.getInputStream());
    boolean flag=true;

    while(flag) {
    System.out.println("     ");
    String msg=br.readLine();
    dos.writeUTF(msg);
    dos.flush();
    //    

     msg=dis.readUTF();
     System.out.println(msg);
    }

     dos.close();
     dis.close();
     client.close();

}
}