📄 udpserver.java
字号:
//package chat;
import java.net.*;
import java.io.*;
public abstract class UDPServer extends Thread {
private int bufferSize; // in bytes
private boolean stopped = false;
protected DatagramSocket ds;
public UDPServer(int port, int bufferSize)
throws SocketException {
this.bufferSize = bufferSize;
this.ds = new DatagramSocket(port);
}
public UDPServer(int port) throws SocketException {
this(port, 8192);
}
public void halt() {
this.stopped = true;
}
/* public void receive(DatagramPacket p) {
byte[] buffer = new byte[65507];
while (true) {
if (stopped) return;
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(dp);
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println(s);
Thread.yield();
}
catch (IOException ex) {
System.err.println(ex);
}
}
}*/
public void run() {
byte[] buffer = new byte[bufferSize];
while (true) {
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(incoming);
this.respond(incoming);
}
catch (IOException e) {
System.err.println(e);
}
} // end while
} // end run
public abstract void respond(DatagramPacket request);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -