📄 udpsend.java
字号:
// 例8.3.5 UDPSend.java
import java.io.*;
import java.net.*;
public class UDPSend
{
private DatagramSocket rese = null;
private DatagramSocket send = null;
public UDPSend()
{
try
{
rese = new DatagramSocket(8082);
send = new DatagramSocket();
new Thread(new ResThread()).start();
new Thread(new SendThread()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
// 通过内部类来创建用于发送消息的线程
class SendThread implements Runnable
{
public void run()
{
byte [] bytes = new byte[1024];
while (true)
{
try
{
System.in.read(bytes);
DatagramPacket sp =
new DatagramPacket(bytes, bytes.length,InetAddress.getLocalHost(), 8083);
send.send(sp);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 通过内部类来创建用于接收消息的线程
class ResThread implements Runnable
{
public void run()
{
byte [] bytes = new byte[1024];
while (true)
{
try
{
DatagramPacket sp = new DatagramPacket(bytes, 1024);
rese.receive(sp);
System.out.println(new String(sp.getData(),0,sp.getLength()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args)
{
new UDPSend();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -