Java UDP implements a chat tool

Topic:
Assuming that Tom and Jerry use Java UDP to chat, please write a program for them. The details are as follows:
(1) Both Tom and Jerry chatting should have a sender and a receiver;
(2) Use DatagramSocket and DatagramPacket;
(3) Implement the java.lang.Runnable class and override the run() method.

Insert picture description here
Anyone who has studied computing networks knows that the use of triples (ip address, protocol, port) can identify the process of the network.
For communication, we can directly use the socket. First, we need to know what the socket is. For this part, you can refer to the blog written by this big guy.
https://blog.csdn.net/pashanhu6402/article/details/96428887 To
implement a client, then both Tom and Jerry need to be able to realize the receiving and sending functions, which are started with two threads respectively.

Receive thread Receive_Thread.java

package Chat_UDP;

import java.io.IOException;
import java.util.Date;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;

public class Receive_Thread extends Thread {
    
    
    private static final int MAX_RECEIVE_BUFFER = 1024;
    private DatagramSocket server;
    private DatagramPacket packet;
    byte[] buffer = new byte[MAX_RECEIVE_BUFFER];
    
    public Receive_Thread(DatagramSocket server)
    {
    
    
        this.server = server;
        packet = new DatagramPacket(buffer, buffer.length);
    }
    
    @Override
    public void run() {
    
    
        try
        {
    
    
            while(true)
            {
    
    
                //接收数据包
                server.receive(packet);
                String s = new String(packet.getData(),packet.getOffset(),packet.getLength(),"UTF-8");
                Date day=new Date();    
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
                if(packet.getPort() == 10001)
                	System.out.println("Tom"+packet.getAddress()+"  说:"+s+"\t"+df.format(day));
                else{
    
    
                	System.out.println("Jerry"+packet.getAddress()+" 说 :"+s+"\t"+df.format(day));
                }
                packet.setLength(buffer.length);
            }
        }
        catch(IOException e)
        {
    
    
            System.out.println("IOException");
        }
    }
}

Send thread Send_Thread.java

package Chat_UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class Send_Thread extends Thread{
    
    
    //发送的socket端
    private DatagramSocket sender = null;
    //待发送的目标地址
    private InetSocketAddress address = null;
    //从键盘输入
    Scanner scan = new Scanner(System.in);
    public Send_Thread(DatagramSocket sender,InetSocketAddress address)
    {
    
    
        this.sender = sender;
        this.address = address;
    }
    
    @Override
    public void run() {
    
    
        // TODO Auto-generated method stub
        try
        {
    
    
            while(true)
            {
    
    
                //输入待发送的内容
                String input = scan.nextLine();
                if(input.equals("exit"))
                    break;
                byte[] data = null;
                data = input.getBytes("UTF-8");
                //创建UDP数据报
                DatagramPacket pack = new DatagramPacket(data, data.length,address);
                sender.send(pack);    
            }
            System.out.println("Exit!");
            
        }catch(IOException e)
        {
    
    
            System.out.println("IOException");
        }
    }

}

Chat server
Chat_Server.java

package Chat_UDP;
//杨丽冰 201831064402
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Chat_Server {
    
    

    private static final int DEST_PORT = 8888;
    private static final int SEND_PORT = 10001;
    private static final int RECE_PORT = 9000;
    private static final String IP = "127.0.0.1";

    public static void main(String[] args)
    {
    
    
        try{
    
    
            Send_Thread send_thread = null;
            Receive_Thread rece_thread = null;
            InetSocketAddress address = null;
            //创建待接受数据包的目的机的端口号和IP地址
            address = new InetSocketAddress(IP, DEST_PORT);
            //创建发送的Socket端
            DatagramSocket sendsocket = new DatagramSocket(SEND_PORT);
            //创建接受的Socket端
            DatagramSocket recesocket = new DatagramSocket(RECE_PORT);
            //发送线程建立
            send_thread = new Send_Thread(sendsocket, address);
            //接受线程的建立
            rece_thread = new Receive_Thread(recesocket);
            send_thread.start();
            rece_thread.start();
        }catch(Exception e)
        {
    
    
            System.out.println("Exception!");
        }

    }

}

Chat client Chat_Client.java

package Chat_UDP;
//杨丽冰 201831064402
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Chat_Client {
    
    
	//声明端口号
    private static final int DEST_PORT = 9000;
    private static final int SEND_PORT = 10000;
    private static final int RECE_PORT = 8888;
    private static final String IP = "127.0.0.1";

    public static void main(String[] args)
    {
    
    
        try{
    
    
            Send_Thread send_thread = null;
            Receive_Thread rece_thread = null;
            InetSocketAddress address = null;
            //创建待接受数据包的目的机的端口号和IP地址
            address = new InetSocketAddress(IP, DEST_PORT);
            //创建发送的Socket端
            DatagramSocket sendsocket = new DatagramSocket(SEND_PORT);
            //创建接受的Socket端
            DatagramSocket recesocket = new DatagramSocket(RECE_PORT);
            //发送线程建立
            send_thread = new Send_Thread(sendsocket, address);
            //接受线程的建立
            rece_thread = new Receive_Thread(recesocket);
            send_thread.start();
            rece_thread.start();

        }catch(Exception e)
        {
    
    
            System.out.println("Exception!");
        }

    }


}

When you need to pay attention, you need to run the chat server and the client at the same time to run normally.
The final effect is as follows:
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/u011612364/article/details/110758853