在线聊天室后端版

实现一个客户可以正常收发消息

聊天室服务端:


/**
 * 在线聊天室:服务端
 * 实现一个客户可以正常收发信息
 * @author fujun
 *
 */

public class Chat{

    public static void main(String[] args) throws Exception {
        System.out.println("---Server----");

        // 1、指定端口使用ServerSocket
        ServerSocket socket = new ServerSocket(8888);
        // 2、阻塞式等待连接accept
        Socket server = socket.accept();
        System.out.println("一个客户端建立连接");

        // 3、接收消息
        DataInputStream dis = new DataInputStream(server.getInputStream());
        String msg = dis.readUTF();
        
        // 4、返回消息
        DataOutputStream dos = new DataOutputStream(server.getOutputStream());
        dos.writeUTF(msg);

        // 释放资源
        dos.flush();
        dos.close();
        dis.close();
        server.close();
    }
}

聊天室客户端:

/**
 * 在线聊天室:客户端
 * 实现一个客户可以正常收发信息
 * @author fujun
 *
 */
public class Client {
    public static void main(String[] args) throws Exception {
        System.out.println("-----Clinet-----");
        // 1、建立连接:使用Socket创建客户端 + 服务端的地址和端口
        Socket client = new Socket("localhost",8888);
        // 2、客户端发送消息
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        String msg = console.readLine();
        
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        dos.writeUTF(msg);
        dos.flush();
        // 获取消息
        DataInputStream dis = new DataInputStream(client.getInputStream());
        msg = dis.readUTF();
        System.out.println(msg);
        
        dos.close();
        dis.close();
        client.close();
    }
}

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_38271653/article/details/85273299
今日推荐