⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpdispatcher.java

📁 一个仿qq的程序源码 一个用纯java开发的
💻 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 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -