Java socket实现简易聊天

你离开我真会死。 提交于 2020-01-31 02:59:48

效果图:
在这里插入图片描述在这里插入图片描述

**

  1. 服务端

**

public class MyServer  {
    public static void main(String[] args) {
        //创建到特定服务端口的套接字0-655535,
        int port = 10086;
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("server is running at"+serverSocket.getLocalSocketAddress());
            //建立套接字,获取socket对象
             Socket socket= serverSocket.accept();
            System.out.println("one client has connected the server,"+socket.getRemoteSocketAddress());

            //收据接收和发送
            while (true){
                //接受
                InputStream is = socket.getInputStream();
                Scanner scanner = new Scanner(is);
                String str = scanner.nextLine();
                System.out.println("client:"+str);
                //发送
                OutputStream os = socket.getOutputStream();
                PrintStream printStream = new PrintStream(os);
                Scanner input = new Scanner(System.in);
                String msg = input.nextLine();
                if("quit".equals(msg)) {
                    break;//结束服务端
                }
                printStream.println(msg);
                printStream.flush();
            }


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

    }

}

2.客户端

ublic class MyClient  {
    public static void main(String[] args) {
        String ip = "127.0.0.1";
        int port = 10086;
        try {
            Socket socket = new Socket(ip,port);
            String line=null;
            while (true){
                Scanner input = new Scanner(System.in);
                line = input.nextLine();
                if("quit".equals(line)) break; //结束客户端
                //发送消息
                OutputStream os = socket.getOutputStream();
                PrintStream printStream = new PrintStream(os);
                printStream.println(line);
                printStream.flush();
                //接受消息
                InputStream is = socket.getInputStream();
                Scanner scanner  =new Scanner(is);
                System.out.println("服务端:"+scanner.nextLine());

            }

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!