如何理解接口幂等性
246
2022-08-29
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];
//创建一个报文,于与接收
Datahttp://gramPacket 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 = STqabDgUVvnew Scanner(System.in);
while (true) {
String str = scan.next();
//要发送的信息
byte[] bytes = str.getBytes();
//发送的目标地址
InetAddress inetAddress = null;
try {
inetAddress = Inehttp://tAddress.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)STqabDgUVv {
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();
}
}
运行结果:
这里实现的是两人聊天,想要实现多人聊天只需要将接受地址改成广播地址即可。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~