📄 udpdispatcher.java
字号:
package qianqian.p2pchat.control;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;
import qianqian.p2pchat.constant.Const;
public class UdpDispatcher extends Dispatcher {
private DatagramSocket udpSocket = null;
private RecvThread recvThread = null;
public UdpDispatcher() throws java.net.SocketException {
udpSocket = new DatagramSocket(Const.SUdpPort);
recvThread = new RecvThread(this, udpSocket);
recvThread.start();
}
private class RecvThread extends Thread {// 接收消息线程
private DatagramSocket udpSocket = null;
private Dispatcher dispatcher = null;
public RecvThread(Dispatcher iDispatcher, DatagramSocket iSock) {
udpSocket = iSock;
dispatcher = iDispatcher;
}
public void run() {
byte inBuf[] = new byte[Const.RecvBufSize];
DatagramPacket recvPack = new DatagramPacket(inBuf,
Const.RecvBufSize);
try {// 循环接受数据
while (!isInterrupted()) {
udpSocket.receive(recvPack);
dispatcher.dataReceived(recvPack.getData(), recvPack
.getLength(), recvPack.getAddress());
}
} catch (Exception ex) {
} finally {
closeDispatcher();
}
}
}
// 广播数据
protected void dispatchToClient(byte iBuf[], int iSize, InetAddress iAddr)
throws Exception {
DatagramPacket disptchPack = new DatagramPacket(iBuf, iSize, iAddr,
Const.CUdpPort);
udpSocket.send(disptchPack);
}
// 关闭套接字
public void closeDispatcher() {
if (recvThread != null) {
recvThread.interrupt();
recvThread = null;
}
if (udpSocket != null) {
udpSocket.close();
udpSocket = null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -