时间:2022-10-28 09:54:54 | 栏目:JAVA代码 | 点击:次
使用UDP实现简单聊天功能,供大家参考,具体内容如下
使用UDP实现一个简单的多人聊天功能。该程序使用了多线程,实现了聊天功能。
package 课后作业.E103_10_聊天; import java.io.IOException; import java.net.*; import java.util.Scanner; //接收 class Receive implements Runnable{ @Override public void run() { DatagramSocket receiveSocket = null; try { receiveSocket = new DatagramSocket(5200); } catch (SocketException e) { e.printStackTrace(); } while (true) { byte[] bytes = new byte[1024]; //创建一个报文,于与接收 DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); //接收 try { receiveSocket.receive(datagramPacket); } catch (IOException e) { e.printStackTrace(); } InetAddress ip = datagramPacket.getAddress(); System.out.println(ip.getHostName()+ new String(datagramPacket.getData())); } } } //发送 class Send implements Runnable{ @Override public void run() { DatagramSocket sendSocket = null; try { sendSocket = new DatagramSocket(); } catch (SocketException e) { e.printStackTrace(); } Scanner scan = new Scanner(System.in); while (true) { String str = scan.next(); //要发送的信息 byte[] bytes = str.getBytes(); //发送的目标地址 InetAddress inetAddress = null; try { inetAddress = InetAddress.getByName("192.168.108.32"); } catch (UnknownHostException e) { e.printStackTrace(); } //数据报文 DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetAddress, 5200); //发送 try { sendSocket.send(datagramPacket); } catch (IOException e) { e.printStackTrace(); } } } } public class Test { public static void main(String[] args) { Receive receive = new Receive(); Thread thread = new Thread(receive); thread.start(); Send send = new Send(); Thread thread1 = new Thread(send); thread1.start(); } }
运行结果:
这里实现的是两人聊天,想要实现多人聊天只需要将接受地址改成广播地址即可。