1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| public class SeverSocket { private Socket socket; private bool isClosed; private Dictionary<string,Client> clientDic = new Dictionary<string,Client>(); public void Start(string ip, int port) { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { socket.Bind(ipEndPoint); isClosed = false; ThreadPool.QueueUserWorkItem(ReceiveMsg); } catch (Exception e) { Console.WriteLine("UDP开启出错"+e.Message); throw; } }
private void CheckTimeout(object obj) { long nowTime = 0; while (true) { Thread.Sleep(30000); nowTime = DateTime.Now.Ticks/TimeSpan.TicksPerSecond; List<string> delList = new List<string>(); foreach (var c in clientDic.Values) { if (nowTime - c.frontTime >= 10) { delList.Add(c.clinetStrID); } } for (int i = 0; i < delList.Count; i++) RemoveClinet(delList[i]); delList.Clear(); } } private void ReceiveMsg(object state) { byte[] bytes = new byte[512]; EndPoint ipPoint = new IPEndPoint(IPAddress.Any, 0); string strID = ""; string ip; int port; while (isClosed) { if (socket.Available>0) { lock (socket) socket.ReceiveFrom(bytes, ref ipPoint); ip = (ipPoint as IPEndPoint).Address.ToString(); port = (ipPoint as IPEndPoint).Port; strID = ip + port; if (clientDic.ContainsKey(strID)) clientDic[strID].ReceiveMsg(bytes); else { clientDic.Add(strID,new Client(ip,port)); clientDic[strID].ReceiveMsg(bytes); } } } } public void SendTo(BaseMsg baseMsg, IPEndPoint ipPoint) { try { lock (socket) socket.SendTo(baseMsg.Writing(), ipPoint); } catch (SocketException e) { Console.WriteLine("发消息出现问题" +e.ErrorCode+ e.Message); } catch (Exception e) { Console.WriteLine("序列化出问题" + e.Message); } } public void BoradcastTo(BaseMsg baseMsg) { foreach (var c in clientDic.Values) { SendTo(baseMsg,c.clientAndpoint); } } public void Close() { if (socket != null) { isClosed = true; socket.Shutdown(SocketShutdown.Both); socket.Close(); socket=null; } } public void RemoveClinet(string clientID) { if (clientDic.ContainsKey(clientID)) { Console.WriteLine("客户端{0}被移除了",clientDic[clientID].clientAndpoint); clientDic.Remove(clientID); } } }
|