java使用UDP实现多人聊天功能
作者:木子_muzi
这篇文章主要为大家详细介绍了java使用UDP实现多人聊天功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
使用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(); } }
运行结果:
这里实现的是两人聊天,想要实现多人聊天只需要将接受地址改成广播地址即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。