udpdispatcher.java

来自「一个仿qq的程序源码 一个用纯java开发的」· Java 代码 · 共 68 行

JAVA
68
字号
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 void dispatchToAll(byte[] iBuf, int iSize)
			throws Exception {
	}

	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()
							.getHostAddress());
				}
			} catch (Exception ex) {
			}
			closeDispatcher();
		}
	}

	// 广播数据
	protected void dispatchToServer(byte iBuf[], int iSize, String iAddr) 
			throws Exception {
		DatagramPacket disptchPack = new DatagramPacket(iBuf, iSize,
				InetAddress.getByName(iAddr), Const.SUdpPort);
		udpSocket.send(disptchPack);
	}

	public UdpDispatcher() throws Exception {
		udpSocket = new DatagramSocket(Const.CUdpPort);
		recvThread = new RecvThread(this, udpSocket);
		recvThread.start();
	}
	
	public void closeDispatcher() {
		if(recvThread != null) {
			recvThread.interrupt();
			recvThread = null;
		}
		if(udpSocket != null && !udpSocket.isClosed()) {
			udpSocket.close();
			udpSocket = null;
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?