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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
| public class UdpNetMgr : MonoBehaviour { private static UdpNetMgr instance; public static UdpNetMgr Instance => instance; private EndPoint serverIpPoint;
private Socket socket; private bool isClosed; private Queue<BaseMsg> sendQueue = new Queue<BaseMsg>(); private Queue<BaseMsg> ReceiveQueue = new Queue<BaseMsg>(); private byte[] cacheBytes = new byte[512]; private void Awake() { instance = this; DontDestroyOnLoad(this); } private void Update() { if (ReceiveQueue.Count > 0) { BaseMsg msg = ReceiveQueue.Dequeue(); switch (msg) { case PlayerMsg playerMsg: print(playerMsg.playerID); print(playerMsg.playerData.name); print(playerMsg.playerData.atk); print(playerMsg.playerData.lev); break; } } }
public void StartClient(string ip, int port) { if (isClosed) return; serverIpPoint = new IPEndPoint(IPAddress.Parse(ip),port); IPEndPoint clientIpPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081); try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(clientIpPoint); isClosed = false; ThreadPool.QueueUserWorkItem(ReceiveMsg); ThreadPool.QueueUserWorkItem(SendMsg); } catch (Exception e) { Console.WriteLine("启动Socket出问题"+e.Message); throw; } } private void SendMsg(object obj) { while (socket!=null&&!isClosed) { if (sendQueue.Count > 0) { try { socket.SendTo(sendQueue.Dequeue().Writing(),serverIpPoint); } catch (SocketException e) { print("发送消息出错"+e.ErrorCode+e.Message); } } } } public void Send(BaseMsg msg) { sendQueue.Enqueue(msg); } private void ReceiveMsg(object obj) { EndPoint tmpIpPoint = new IPEndPoint(IPAddress.Any, 0); int nowIndex; int msgID; int msgLength; while (socket!=null&&!isClosed) { if (socket.Available>0) { try { socket.ReceiveFrom(cacheBytes, ref tmpIpPoint); if (!tmpIpPoint.Equals(serverIpPoint)) continue; nowIndex = 0; msgID = BitConverter.ToInt32(cacheBytes, nowIndex); nowIndex += 4; msgLength = BitConverter.ToInt32(cacheBytes, nowIndex); nowIndex += 4; BaseMsg msg = null; switch (msgID) { case 1001: msg = new PlayerMsg(); msg.Reading(cacheBytes, nowIndex); break; } if (msg != null) ReceiveQueue.Enqueue(msg); } catch (SocketException e) { print("接收消息出问题" + e.ErrorCode + e.Message); } catch (Exception e) { print("接收消息出问题(非网络)" + e.Message); } } } } public void Close() { if (socket != null) { isClosed = true; socket.Shutdown(SocketShutdown.Both); socket.Close(); socket = null; } }
private void OnDestroy() { Close(); } }
|