编程语言
首页 > 编程语言> > java UDP实现一个聊天工具

java UDP实现一个聊天工具

作者:互联网

题目:
假设Tom和Jerry利用Java UDP进行聊天,请为他们编写程序。具体如下:
(1)、Tom和Jerry聊天的双方都应该具有发送端和接收端;
(2)、利用DatagramSocket与DatagramPacket;
(3)、实现 java.lang.Runnable类,重写 run()方法。

在这里插入图片描述
学过计网的都知道,利用三元组(ip地址,协议,端口)就可以标识网络的进程了。
而进行通信我们直接运用socket就可以了,首先需要知道是socket是什么,这部分可以参考这个大佬写的博客。
https://blog.csdn.net/pashanhu6402/article/details/96428887
实现一个客户端,那么需要Tom和Jerry都可以实现接收和发送功能,分别用两个线程启动。

接收线程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.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.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.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!");
        }

    }


}

标签:DatagramSocket,UDP,java,Thread,private,聊天工具,import,new
来源: https://blog.csdn.net/u011612364/article/details/110758853