UDP试下数据传输 简单的聊天

本文介绍了一个使用 Java 实现的 UDP 聊天室程序,该程序通过创建发送端和接收端两个线程来实现即时消息的收发功能。发送端使用 DatagramSocket 发送消息到指定 IP 和端口,接收端则监听特定端口接收消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package itecat.zpf.netudpp;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class UDPChat {
public static void main(String[] args) throws SocketException {
// 实现群聊
// 即收也能发 需要用到多线程 需要两个任务


DatagramSocket sendsocket = new DatagramSocket();
DatagramSocket Recesocket = new DatagramSocket(10003);

Send send = new Send(sendsocket);
Rece rece = new Rece(Recesocket);

Thread t1 = new Thread(send);
Thread t2 = new Thread(rece);
t1.start();
t2.start();
}
}


class Send implements Runnable {

private DatagramSocket ds;

public Send(DatagramSocket ds) {
super();
this.ds = ds;
}


@Override
public void run() {
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = buff.readLine()) != null) {
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.81.105"), 10003);
ds.send(dp);
if ("over".equals(line)) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}


// 接收任务
class Rece implements Runnable {
private DatagramSocket ds;


public Rece(DatagramSocket ds) {
super();
this.ds = ds;
}


@Override
public void run() {
while (true) {
try {
// udp接受数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String text = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip + ": " + port + "   " + text);
if (text.equals("over")) {
System.out.println(ip + "已经离开");
}
// ds.close();


} catch (Exception e) {
e.printStackTrace();
}


}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值