socket辅助类
using System; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace PYC.FileTransfer.Common.SocketHelp000000000000000000000 { public delegate void NetSockErr(object sender, NetArgs e); public delegate void NetConnect(object sender, NetArgs e); public delegate void NetReceiveMsg(object sender, NetArgs e); public delegate void NetDisConnect(object sender, NetArgs e); public class TCPSockClient : TCPSock { public event NetSockErr OnSockErr; public event NetConnect OnConnect; public event NetReceiveMsg OnReceiveMsg; public event NetDisConnect OnDisConnect; private bool online = false; public Socket ClientSocket;//客户端网络连接 private Thread ThreadClientReceive;//客户端接收聊天信息线程 private int _ServerPort; private IPAddress _ServerIP; private byte[] data = new byte[1024]; private int sent; public int ServerPort { get { return _ServerPort; } } public IPAddress ServerIP { get { return _ServerIP; } } /// <summary> /// 构造函数 /// </summary> /// <param name="p">服务端端口</param> /// <param name="ip">服务端IP</param> /// <param name="f">form</param> /// <param name="neh">委托</param> public TCPSockClient(string ip, int port) { _ServerPort = port; _ServerIP = IPAddress.Parse(ip); } public void Connect(string name) { ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint remoteEP = new IPEndPoint(_ServerIP, _ServerPort);//建立客户端网络端点 try { ClientSocket.Connect(remoteEP); } catch (SocketException e) { if (OnSockErr != null) { args.Msg = "连接远程服务器失败:" + e.Message; OnSockErr(this, args); } return; } this_Connect(name); Thread.Sleep(200); ThreadClientReceive = new Thread(new ThreadStart(ClientReceive)); ThreadClientReceive.IsBackground = true; ThreadClientReceive.Start(); } private void this_Connect(string name) { Send("Online|" + name); if (OnConnect != null) { NetArgs na = new NetArgs(name); OnConnect(this, na); } } private void ClientReceive()//客户端开始接收信息 { online = true; try { while (online) { if (ClientSocket == null || ClientSocket.Available < 1) { Thread.Sleep(200); continue; } data = PreVarReceive(ClientSocket); string msg = Encoding.Default.GetString(data); if (msg != "") { string[] arr = msg.Split('|'); switch (arr[0]) { case "Exit": DisConnect(); return; break; default: if (OnReceiveMsg != null) { NetArgs na = new NetArgs(msg); OnReceiveMsg(this, na); } break; } } Thread.Sleep(200); } } catch (Exception e) { if (OnSockErr != null) { args.Msg = "客户端接收信息失败:" + e.Message; OnSockErr(this, args); } } } public void Send(string msg) { try { sent = PreVarSend(ClientSocket, Encoding.Default.GetBytes(msg)); } catch (Exception e) { if (OnSockErr != null) { args.Msg = "客户端发送信息失败:" + e.Message; OnSockErr(this, args); } } } public void DisConnect() { Send("Exit"); Thread.Sleep(200); online = false; if (ClientSocket.Connected) { ClientSocket.Shutdown(SocketShutdown.Both); } ClientSocket.Close(); Thread.Sleep(200); if (ThreadClientReceive.IsAlive) { ThreadClientReceive.Abort(); } if (OnDisConnect != null) { NetArgs na = new NetArgs(""); OnDisConnect(this, na); } } } public class TCPSockServer : TCPSock { public event NetSockErr OnSockErr; public event NetConnect OnConnect; public event NetReceiveMsg OnReceiveMsg; public event NetDisConnect OnDisConnect; public bool servering = false; private Socket SocketListener; public Socket ClientSocket; private Thread ThreadListener;//服务器端侦听线程 private Hashtable _clients; private int _port; private int _maxBackLog; private string _serverip; private byte[] data = new byte[1024]; public Hashtable Clients { get { return _clients; } } public int Port { get { return _port; } } public int MaxBackLog { get { return _maxBackLog; } } public string serverip { get { return this._serverip; } } /// <summary> /// 构造函数 /// </summary> /// <param name="p">端口</param> /// <param name="m">列队</param> public TCPSockServer(string ip, int p, int m) { _serverip = ip; _port = p; _maxBackLog = m; _clients = new Hashtable(); } public void StartServer() { ThreadListener = new Thread(new ThreadStart(StartListen)); ThreadListener.IsBackground = true; ThreadListener.Start();//新开一个线程,用于接收客户端的连接 } public void StopServer() { StopListen();//结束侦听,并结束接收信息 } private void StartListen() { servering = true; try { SocketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(_serverip), _port); SocketListener.Bind(remoteEP); SocketListener.Listen(_maxBackLog); while (servering) { Socket ServerSocket = SocketListener.Accept(); ClientSocket = ServerSocket; if (_clients.Count >= _maxBackLog || !servering) { ServerSocket.Close(); } else { Client client = new Client(ServerSocket); client.thread = new Thread(new ParameterizedThreadStart(ServerReceive)); client.thread.IsBackground = true; client.thread.Start(client); } Thread.Sleep(200); } } catch (Exception e) { if (OnSockErr != null) { args.Msg = "服务端开始侦听发生错误:" + e.Message; OnSockErr(this, args); } StopListen();//结束侦听 } } private void ServerReceive(object ThreadData) { Client client = (Client)ThreadData; try { while (client.online && servering) { if (client.socket == null || client.socket.Available < 1) { Thread.Sleep(200); continue; } data = PreVarReceive(client.socket); string msg = Encoding.Default.GetString(data); if (msg != "") { string[] arr = msg.Split('|'); switch (arr[0]) { case "Online": client.name = arr[1]; if (!Add(client)) return; break; case "Exit": Remove(client); return; case "RequestSendFile": if (OnReceiveMsg != null) { NetArgs na = new NetArgs(client.name + "|" + msg); OnReceiveMsg(this, na); } break; case "ResposeSendFile": if (OnReceiveMsg != null) { NetArgs na = new NetArgs(client.name + "|" + msg); OnReceiveMsg(this, na); } break; } } Thread.Sleep(200); } } catch (Exception e) { if (OnSockErr != null) { args.Msg = "服务端侦听发生错误:" + e.Message; OnSockErr(this, args); } } } private bool Add(Client client) { if (!_clients.Contains(client.name)) { _clients.Add(client.name, client); if (OnConnect != null) { NetArgs na = new NetArgs(client.name); OnConnect(this, na); } return true; } return false; } private void Remove(Client client) { if (_clients.ContainsKey(client.name)) { client.online = false; if (client.socket != null) { client.socket.Close(); } Thread.Sleep(200); if (client.thread.IsAlive) { client.thread.Abort(); } if (OnDisConnect != null) { NetArgs na = new NetArgs(client.name); OnDisConnect(this, na); } Thread.Sleep(200); _clients.Remove(client.name); } } public void Send(Client c, string msg) { try { data = Encoding.Default.GetBytes(msg); int sent = PreVarSend(c.socket, data); } catch (Exception e) { if (OnSockErr != null) { args.Msg = "服务端发送信息失败:" + e.Message; OnSockErr(this, args); } } } private void StopListen()//结束侦听,并结束接收信息 { servering = false; lock (_clients.SyncRoot) { foreach (DictionaryEntry de in _clients) { Client c = (Client)de.Value; if (c.socket != null) { c.socket.Shutdown(SocketShutdown.Both); c.socket.Close(); } Thread.Sleep(1000); if (c.thread.IsAlive) { c.thread.Abort(); } Thread.Sleep(200); } _clients.Clear(); } SocketListener.Close();//关闭服务器侦听连接 Thread.Sleep(1000); ThreadListener.Abort();//关闭服务器侦听线程 } } public class Client { public bool online; public Socket socket; public Thread thread; private string _name; private string _remoteIP; public string name { set { _name = value; } get { return _name; } } public string remoteIP { get { return _remoteIP; } } public Client(Socket s) { online = true; socket = s; _remoteIP = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); } } public abstract class TCPSock { public NetArgs args = new NetArgs(""); public byte[] PreVarReceive(Socket s) { int total = 0, recv; byte[] datasize = new byte[4]; recv = s.Receive(datasize, 0, 4, 0); int size = BitConverter.ToInt32(datasize, 0); int dataleft = size; byte[] data = new byte[size]; while (total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { data = Encoding.Default.GetBytes("Exit"); break; } total += recv; dataleft -= recv; } return data; } public int PreVarSend(Socket s, byte[] data) { int total = 0; int size = data.Length; int dataleft = size; int sent; byte[] datasize = new byte[4]; datasize = BitConverter.GetBytes(size); sent = s.Send(datasize); while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } } private class NetArgs : EventArgs { public string Msg; public NetArgs(string m) { Msg = m; } } public class UDP { public event NetReceiveMsg OnReceiveMsg; public bool ListenerDone = false; private int listenPort; private Thread listenerThread; private UdpClient listener; public int ListenPort { get { return listenPort; } } public UDP(int l) { listenPort = l; } public void StartReceive() { ListenerDone = false; listenerThread = new Thread(new ThreadStart(StartListener)); listenerThread.IsBackground = true; listenerThread.Start(); } private void StartListener() { listener = new UdpClient(listenPort); //任意IP,设端口为0表示任意 IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); try { while (!ListenerDone) { byte[] bytes = listener.Receive(ref groupEP); string strIP = groupEP.Address.ToString(); string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length); if (strInfo != null && strInfo != "" && OnReceiveMsg != null) { NetArgs na = new NetArgs("来自" + strIP + ":" + strInfo); OnReceiveMsg(this, na); } Thread.Sleep(200); } } catch { listener.Close(); } } public void Send(IPAddress broadcast, string data) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] sendbuf = Encoding.GetEncoding("gb2312").GetBytes(data); IPEndPoint ep = new IPEndPoint(broadcast, listenPort); s.SendTo(sendbuf, ep); } public void StopReceive() { ListenerDone = true; listener.Close(); Thread.Sleep(200); if (listenerThread.IsAlive) { listenerThread.Abort(); } } } }