[java] Simulate WeChat chat (network programming)

Simulate WeChat chat (network programming)

Nowadays, WeChat chat has become an indispensable and important part of people's lives, and many of people's communications are carried out through WeChat. This case requires the combination of multi-threading and UDP communication-related knowledge to simulate the implementation of a chat applet between two WeChat friends in a local area network.

The overall requirements of the program are as follows: When the program is started, the user is asked to enter his or her WeChat ID and that of his friends. The program creates two threads (message sending thread and message receiving thread) to start the LAN chat system.

Special reminder:
1. In order to achieve communication within the local area network, when users send messages, they do so through the broadcast (group sending) function. When sending a message, set the target IP address to 127.0.0.255. (Of course, you can also use the other party’s IP address directly.)

2. WeChat ID is actually the port number used to receive data. For example, Zhang San’s WeChat ID is 5001, and Li Si’s WeChat ID is 5008. Then Zhang San monitors and receives messages on port 5001, while Li Si monitors and receives messages on port 5008. When Zhang San sends a message to Li Si, he actually sends a data packet to the 5008 port number of the broadcast address. Similarly, when Li Si sends a message to Zhang San, he actually sends a data packet to the 5001 port number of the broadcast address.

3. In order to facilitate debugging the program, we hope to start two programs at the same time on the same machine. In this case, we need to execute the same program twice in the IDE to start the running instances of the two programs.

【mission target】

 Learn to analyze the implementation ideas of the task of “simulating WeChat chat”.
 Independently complete the source code writing, compilation and operation of the "simulating WeChat chat" task based on ideas.

 Master the programming principles of UDP protocol in network communication.

 Master the use of UDP network communication DatagramPacket and DatagramSocket.

[Implementation ideas]

This program involves multi-threading and can use interface-based multi-threading implementation technology.

1. Write the thread class SendTask for sending messages. The main function of this class is to create a socket object and a packet object in its run method, obtain the text entered by the keyboard, and then send it to the friend port at the 127.0.0.255 address. Number.

2. Write the thread class ReceiveTask to receive messages. The main function of this class is to create socket objects and packet objects in its run method, listen (receive) messages at the specified port number, and print them out.

Write the main class Room, obtain the user's WeChat ID and friends' WeChat ID in the main method, create and start the sending thread and receiving thread respectively.

Special note: Since the user WeChat ID (port number, 5001 in the demo program) is passed to the sending thread object in the main method. Therefore, we can add an int member attribute sendPort to the SendTask class, add a constructor with parameters, and initialize it when creating the object in the main method. Similarly, add an int member attribute receivePort to the ReceiveTask class, and pass the friend's WeChat ID (port number, 5008 in the demo program) to the receiving thread object.

[Implementation code]
1. SendTask class

package cn.edu.gpnu.bank.cn.edu.gpnu.exp13;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class SendTask implements Runnable {
    
    
    private int sendPort; // 发消息的微信号(端口号)

    public SendTask(int sendPort) {
    
    
        this.sendPort = sendPort;
    }
    @Override
    public void run() {
    
    
        try {
    
    
            // 1. 创建 DatagramSocket 对象 ds
            DatagramSocket ds=new DatagramSocket();
            InetAddress inetAddress = InetAddress.getByName("127.0.0.255");
            Scanner sc = new Scanner(System.in);
            while (true) {
    
    
                // 2. 获取键盘输入的信息
                String str=sc.nextLine();
                // 3. 将消息转换为字节数组,再将其封装到 DatagramPacket 对象 dp 中
                byte[] arr=str.getBytes();
                DatagramPacket dp=new DatagramPacket(arr,arr.length,inetAddress,sendPort);
                // 4.ds 发送数据 dp
                ds.send(dp);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

2. ReceiveTask class

package cn.edu.gpnu.bank.cn.edu.gpnu.exp13;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveTask implements Runnable{
    
    
    private int receivePort;// 接收数据的端口号

    public ReceiveTask(int receivePort) {
    
    
        this.receivePort = receivePort;
    }

    //补充构造方法
    @Override
    public void run() {
    
    
        try {
    
    
            // 1.DatagramSocket 对象 ds
            DatagramSocket ds=new DatagramSocket(receivePort);
            // 2.创建字节数组和 DatagramPacket 对象 dp
            byte [] buf=new byte[1024];
            DatagramPacket dp=new DatagramPacket(buf,buf.length);
            //补充代码
            while (true) {
    
    
                // 3.ds 接收数据 sp
                ds.receive(dp);
                // 4.接收到的数据转化为字符串,并打印显示
                String str = "【"+dp.getAddress().getHostAddress()+"】:"+new String(dp.getData(),0, dp.getLength());
                System.out.println(str);
            }

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

3. Room class

package cn.edu.gpnu.bank.cn.edu.gpnu.exp13;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Room {
    
    
    public static void main(String[] args) {
    
    
        //显示欢迎信息,获取用户微信号和好友微信号。
        System.out.println("欢迎进入模拟微信系统!");
        //补充代码
        //创建发送消息线程对象(传递用户微信号)并启动。
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入您的微信号(端口号):");
        int sendPort=sc.nextInt();
        SendTask s=new SendTask(sendPort);
        //补充代码
        //创建接收消息线程对象(传递好友微信号)并启动。
        System.out.println("请输入您的好友微信号(端口号):");

        int receivePort=sc.nextInt();
        ReceiveTask r=new ReceiveTask(receivePort);
        //补充代码
        System.out.println("微信聊天室已启动!");
        new Thread(s).start();
        new Thread(r).start();
    }

}

【operation result】
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/m0_52703008/article/details/126324839