private void ReceiveUdp(IAsyncResult packet) { IPEndPoint remote = (IPEndPoint)Udp.Client.RemoteEndPoint; byte[] received = Udp.EndReceive(packet, ref remote); LocalConsole.Instance.Log("Received a packet", true); MsgType type = GetMsgType(received); string msg; LocalConsole.Instance.Log("type is " + type, true); LocalConsole.Instance.Log("msg is " + Encoding.ASCII.GetString(ScrubSubheader(received)), true); switch (type) { case MsgType.POS: case MsgType.STATE: case MsgType.STATUS: msg = Encoding.ASCII.GetString(ScrubSubheader(received)); if (msg.Equals("0")) { LocalConsole.Instance.Log("Server reporting shutdown, disconnecting...", true); Disconnect(); } break; case MsgType.MSG: // Default to MSG default: msg = Encoding.ASCII.GetString(ScrubSubheader(received)); LocalConsole.Instance.Log("Received [" + type + "] " + msg + " from " + remote.Address + " on port " + remote.Port); break; } }
/// <summary> /// Send a message to an address via UDP /// </summary> /// <returns>Returns client-side success as bool</returns> public bool SendMsgUdp(string nMsg, MsgType nType = MsgType.MSG) { if (Ready) { if (Connected) { byte[] arr = Encoding.ASCII.GetBytes(nMsg); UdpSend = AssemblePacket(arr, nType); if (UdpSend != null && UdpSend.Length > 0) { int numBytes = Udp.Send(UdpSend, UdpSend.Length); // LocalConsole.Instance.Log("Sent " + numBytes + " bytes"); return(true); } else { LocalConsole.Instance.Log("Invalid message data to send"); return(false); } } else { LocalConsole.Instance.Log("Not currently connected to a server"); return(false); } } else { LocalConsole.Instance.Log("HubrisNet is not ready"); return(false); } }
/// <summary> /// Creates a client with the id. /// </summary> Client(int id, ServerConfigs configs) { Id = id; _tcpConnection = new Tcp(Id, configs); _udpConnection = new Udp(Id, configs); }
unsafe internal static extern int uv_udp_send( UdpRequest request, Udp udp, Structs.Buffer *buffers, int nbufs, ref NativeSocketAddress address, uv_udp_send_cb callback);
public async Task NetworkTimeProtocol() { var cs = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var server = await new MultiAddress("/dns4/time.windows.com/udp/123").ResolveAsync(cs.Token); var ntpData = new byte[48]; ntpData[0] = 0x1B; var udp = new Udp(); await using (var time = await udp.ConnectAsync(server[0], cs.Token)) { ntpData[0] = 0x1B; await time.WriteAsync(ntpData, 0, ntpData.Length, cs.Token); await time.FlushAsync(cs.Token); await time.ReadAsync(ntpData, 0, ntpData.Length, cs.Token); Assert.AreNotEqual(0x1B, ntpData[0]); Array.Clear(ntpData, 0, ntpData.Length); ntpData[0] = 0x1B; await time.WriteAsync(ntpData, 0, ntpData.Length, cs.Token); await time.FlushAsync(cs.Token); await time.ReadAsync(ntpData, 0, ntpData.Length, cs.Token); Assert.AreNotEqual(0x1B, ntpData[0]); } }
public async Task Listen() { var udp = new Udp(); var cs = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var connected = false; void Handler(Stream stream, MultiAddress local, MultiAddress remote) { Assert.IsNotNull(stream); connected = true; } try { var listenerAddress = udp.Listen("/ip4/127.0.0.1", Handler, cs.Token); Assert.IsTrue(listenerAddress.Protocols.Any(p => p.Name == "udp")); await using (var stream = await udp.ConnectAsync(listenerAddress, cs.Token)) { await Task.Delay(50, cs.Token); Assert.IsNotNull(stream); Assert.IsTrue(connected); } } finally { cs.Cancel(); } }
public void Run() { this.closeCount = 0; this.serverSendCount = 0; this.clientReceiveCount = 0; this.loop = new Loop(); var endPoint = new IPEndPoint(IPAddress.Loopback, Port); Udp client = this.loop .CreateUdp() .ReceiveStart(endPoint, this.OnClientReceive); IPAddress group = IPAddress.Parse("239.255.0.1"); client.JoinGroup(group); byte[] data = Encoding.UTF8.GetBytes("PING"); Udp server = this.loop.CreateUdp(); server.QueueSend(data, endPoint, this.OnServerSendCompleted); this.loop.RunDefault(); Assert.Equal(2, this.closeCount); Assert.Equal(1, this.serverSendCount); Assert.Equal(1, this.clientReceiveCount); Assert.Null(this.sendError); Assert.Null(this.receiveError); }
/// <summary> /// Used for accepting connections and registering clients /// </summary> protected override void UDP() { DebugInfo("UDP process started."); while (serverUp) { try { IPEndPoint tmp = new IPEndPoint(IPAddress.Any, Udp.PortUDP); var data = Udp.RecieveMessage(ref tmp); if (data != null) { // New request DebugInfo("Crearting new thread to attend the Udp request."); Thread t = new Thread(() => UdpRequests(data, tmp)); t.Start(); } } catch (Exception e) { DebugInfo("Unexpected error UDP: " + e.ToString()); } } DebugInfo("UDP Service is down."); }
public void Udp() { this.closeCount = 0; var anyEndPoint = new IPEndPoint(IPAddress.Any, Port); Udp udp = this.loop .CreateUdp() .ReceiveStart(anyEndPoint, this.OnReceive); this.server = udp; IPEndPoint localEndPoint = udp.GetLocalEndPoint(); Assert.NotNull(localEndPoint); Assert.Equal(anyEndPoint.Address, localEndPoint.Address); Assert.Equal(Port, localEndPoint.Port); Udp client = this.loop.CreateUdp(); var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, Port); byte[] data = Encoding.UTF8.GetBytes("PING"); client.QueueSend(data, remoteEndPoint, this.OnSendCompleted); this.loop.RunDefault(); Assert.Equal(1, this.connectedCount); Assert.Equal(1, this.connectionCount); Assert.Equal(2, this.closeCount); }
public void Run(bool dualStack) { if (!Platform.OSSupportsIPv6) { return; } this.sendCount = 0; this.receiveCount = 0; this.closeCount = 0; var endPoint = new IPEndPoint(IPAddress.IPv6Any, Port); this.server = this.loop .CreateUdp() .ReceiveStart(endPoint, this.OnReceive, dualStack); // Dual byte[] data = Encoding.UTF8.GetBytes("PING"); var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, Port); this.client = this.loop.CreateUdp(); this.client.QueueSend(data, remoteEndPoint, this.OnSendCompleted); this.loop.CreateTimer() .Start(this.OnTimer, 500, 0); this.loop.RunDefault(); Assert.Equal(1, this.sendCount); // IPv6 only should not receive from IPv4 Assert.Equal(!dualStack ? 0 : 1, this.receiveCount); Assert.Equal(3, this.closeCount); }
void OnSendCompleted(Udp udp, Exception exception) { if (exception == null) { this.sendCount++; } }
static void OnReceive(Udp udp, IDatagramReadCompletion completion) { if (completion.Error != null) { completion.Dispose(); Console.WriteLine($"{nameof(EchoServer)} receive error {completion.Error}"); udp.ReceiveStop(); udp.CloseHandle(OnClose); return; } ReadableBuffer data = completion.Data; string message = data.ReadString(Encoding.UTF8); data.Dispose(); IPEndPoint remoteEndPoint = completion.RemoteEndPoint; if (string.IsNullOrEmpty(message) || remoteEndPoint == null) { return; } WritableBuffer buffer = WritableBuffer.From(Encoding.UTF8.GetBytes(message)); udp.QueueSend(buffer, remoteEndPoint, OnSendCompleted); }
void OnReceive(Udp udp, IDatagramReadCompletion completion) { var error = completion.Error as OperationException; if (error != null && error.ErrorCode == ErrorCode.ECANCELED) // UV_ECANCELED { return; } ReadableBuffer data = completion.Data; if (data.Count == 0) { return; } string message = data.ReadString(data.Count, Encoding.UTF8); if (message != ExpectedMessage) { Console.WriteLine( $"Udp pummel {this.numberOfSenders}v{this.numberOfReceivers} failed, wrong message '{message}' received."); } this.receiveCount++; }
public void Run() { this.closeCount = 0; this.serverSendCount = 0; this.loop = new Loop(); var anyEndPoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort); Udp server = this.loop .CreateUdp() .Bind(anyEndPoint) .MulticastTtl(32); /* server sends "PING" */ byte[] data = Encoding.UTF8.GetBytes("PING"); IPAddress address = IPAddress.Parse("239.255.0.1"); var endPoint = new IPEndPoint(address, Port); server.QueueSend(data, endPoint, this.OnServerSendCompleted); this.loop.RunDefault(); Assert.Equal(1, this.closeCount); Assert.Equal(1, this.serverSendCount); }
static void OnReceive(Udp udp, IDatagramReadCompletion completion) { if (completion.Error != null) { Console.WriteLine($"Echo server receive error {completion.Error}"); udp.CloseHandle(OnClosed); return; } IPEndPoint remoteEndPoint = completion.RemoteEndPoint; ReadableBuffer data = completion.Data; string message = data.Count > 0 ? data.ReadString(data.Count, Encoding.UTF8) : null; if (string.IsNullOrEmpty(message)) { return; } Console.WriteLine($"Echo server received : {message} from {remoteEndPoint}"); Console.WriteLine($"Echo server sending echo back to {remoteEndPoint}."); byte[] array = Encoding.UTF8.GetBytes($"ECHO [{message}]"); WritableBuffer buffer = WritableBuffer.From(array); udp.QueueSend(buffer, remoteEndPoint, OnSendCompleted); }
public void Run() { this.closeCount = 0; this.clientReceiveCount = 0; this.clientSendCount = 0; this.serverReceiveCount = 0; this.serverSendCount = 0; this.loop = new Loop(); var anyEndPoint = new IPEndPoint(IPAddress.Any, Port); this.loop .CreateUdp() .ReceiveStart(anyEndPoint, this.OnServerReceive); Udp client = this.loop.CreateUdp(); byte[] data = Encoding.UTF8.GetBytes("PING"); var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, Port); client.QueueSend(data, remoteEndPoint, this.OnClientSendCompleted); this.loop.RunDefault(); Assert.Equal(1, this.clientSendCount); Assert.Equal(1, this.serverSendCount); Assert.Equal(1, this.serverReceiveCount); Assert.Equal(1, this.clientReceiveCount); Assert.Equal(2, this.closeCount); Assert.Null(this.serverSendError); }
public void Bind(bool reuseAddress) { var endPoint = new IPEndPoint(IPAddress.Loopback, Port); Udp udp1 = this.loop.CreateUdp(); udp1.Bind(endPoint, reuseAddress); Udp udp2 = this.loop.CreateUdp(); if (reuseAddress) { udp2.Bind(endPoint, true); } else { var error = Assert.Throws <OperationException>(() => udp2.Bind(endPoint)); Assert.Equal(ErrorCode.EADDRINUSE, error.ErrorCode); } udp1.CloseHandle(this.OnClose); udp2.CloseHandle(this.OnClose); this.loop.RunDefault(); Assert.Equal(2, this.closeCount); }
/// <summary> /// Close all connections and stop all coroutines /// </summary> public void Disconnect() { if (Connected) { // Null check to prevent errors on closing application without disconnecting if (Tcp != null && Tcp.Connected) { Tcp.Close(); } if (_tcpCo != null) { StopCoroutine(_tcpCo); _tcpCo = null; } // Null check to prevent errors on closing application without disconnecting if (Udp != null) { Udp.Close(); } Connected = false; } else { LocalConsole.Instance.Log("Not currently connected"); } }
private void DiscoveringUsers() { Random random = new Random(); while (this.discoveringThread.IsAlive) { try { FilterTimeoutUsers(); try { Udp.SendBroadcast(Helper.XmlSerialize <RequestPresence>(new RequestPresence() { Status = "ask", UserAddress = new UserAddress() { Address = Helper.LocalIPAddress(), Port = Udp.DefaultPort }, UserInfo = null })); Log.WriteLn("Send: ask - broadcast"); } catch { } Thread.Sleep(random.Next(8000, 14000)); } catch { } } }
internal override void SendPings() { _forwarders.ForEach(fwd => { Udp.Tell(new SendMessage(fwd, new IndirectPing(SeqNo, _target))); }); }
public async Task Stop() { if (IsDestroyed) { return; } try { if (Udp != null) { await Udp.Stop(); } if (Tcp != null) { await Tcp.CloseAsync(); } } catch (Exception) { } finally { OnDestroyed?.Invoke(this); } Tcp = null; Udp = null; IsDestroyed = true; }
void OnReceive(Udp udp, IDatagramReadCompletion completion) { if (completion.Error != null || completion.RemoteEndPoint == null) { return; } ReadableBuffer buffer = completion.Data; if (buffer.Count == 0) { return; } string message = buffer.ReadString(buffer.Count, Encoding.UTF8); if (message == "PING" || message == "PANG") { this.serverReceiveCount++; } if (this.serverReceiveCount == 2) { udp.CloseHandle(this.OnClose); } }
public void disconnect() { if (!isConnected) { return; } isConnected = false; PlayerController player = getPlayerById(id); if (player == null) { return; } player.removePlayer(); removeFromPlayers(id); tcp.disconnect(); udp.disconnect(); tcp = null; udp = null; MenuController.instance.setLog("Disconnected from server!"); }
private void btnCountDown_Click(object sender, RoutedEventArgs e) { TscData t = Utils.Utils.GetTscDataByApplicationCurrentProperties(); string result = ""; if ((bool)cbxCountDown.IsChecked) { if ((bool)rbn15CountDown.IsChecked) { bool b1 = Udp.sendUdpNoReciveData(t.Node.sIpAddress, t.Node.iPort, Define.SET_COUNT_DOWN_OPEN_15); if (b1) { result = "倒计时开启成功,15秒后进行倒计时操作成功!"; } else { result = "倒计时开启失败,15秒后进行倒计时操作失败!"; } } else if ((bool)rbnNormalCountDown.IsChecked) { bool b2 = Udp.sendUdpNoReciveData(t.Node.sIpAddress, t.Node.iPort, Define.SET_COUNT_DOWN_OPEN_NORMAL); if (b2) { result = "倒计时开启成功,正常进行倒计时操作成功!"; } else { result = "倒计时开启失败,正常进行倒计时操作失败!"; } } else if ((bool)rbnPauseCountDown.IsChecked) { bool b3 = Udp.sendUdpNoReciveData(t.Node.sIpAddress, t.Node.iPort, Define.SET_COUNT_DOWN_OPEN_8); if (b3) { result = "倒计时开启成功,8秒停止进行倒计时操作成功!"; } else { result = "倒计时开启失败,8秒停止进行倒计时操作失败!"; } } } else { bool b4 = Udp.sendUdpNoReciveData(t.Node.sIpAddress, t.Node.iPort, Define.SET_COUNT_DOWN_CLOSE); if (b4) { result = "倒计时关闭成功!"; } else { result = "倒计时关闭失败!"; } } MessageBox.Show(result); }
public void Connect(string hostName, string name) { Name = name; ConnectionState = Networking.ConnectionState.Connecting; Tcp.Connect(hostName); Udp.Connect(hostName); }
static void OnSendCompleted(Udp udp, Exception exception) { if (exception != null) { udp.CloseHandle(OnClose); Console.WriteLine($"{nameof(EchoServer)} send error {exception}"); } }
void OnReceive(Udp udp, IDatagramReadCompletion completion) { if (completion.Error == null && completion.Data.Count > 0) { this.receiveCount++; } }
static void OnSendCompleted(Udp udp, Exception exception) { if (exception != null) { Console.WriteLine($"Echo server send error {exception}"); udp.CloseHandle(OnClosed); } }
public void Disconnect(int reason) { //TODO handle reason Udp.Close(); Tcp.Disconnect(false); Tcp.Close(); }
public void Close() { Udp.Close(); Tcp.Close(); Udp = null; Tcp = null; }
public void RunTest(IPEndPoint ep) { int close_cb_called = 0; int cl_send_cb_called = 0; int cl_recv_cb_called = 0; int sv_send_cb_called = 0; int sv_recv_cb_called = 0; Udp client = new Udp(); Udp server = new Udp(); server.Bind(ep); server.Message += (msg) => { var data = msg.Payload; var str = Encoding.ASCII.GetString(data.Array, data.Offset, data.Count); Assert.Equal(str, "PING"); sv_recv_cb_called++; server.Send(msg.EndPoint, Encoding.ASCII.GetBytes("PONG"), (s) => { sv_send_cb_called++; server.Close(() => close_cb_called++); }); }; server.Resume(); client.Send(ep, Encoding.ASCII.GetBytes("PING"), (s) => { cl_send_cb_called++; client.Message += (msg) => { var data = msg.Payload; var str = Encoding.ASCII.GetString(data.Array, data.Offset, data.Count); Assert.Equal(str, "PONG"); cl_recv_cb_called++; client.Close(() => close_cb_called++); }; client.Resume(); }); Assert.Equal(0, close_cb_called); Assert.Equal(0, cl_send_cb_called); Assert.Equal(0, cl_recv_cb_called); Assert.Equal(0, sv_send_cb_called); Assert.Equal(0, sv_recv_cb_called); Loop.Default.Run(); Assert.Equal(2, close_cb_called); Assert.Equal(1, cl_send_cb_called); Assert.Equal(1, cl_recv_cb_called); Assert.Equal(1, sv_send_cb_called); Assert.Equal(1, sv_recv_cb_called); #if DEBUG Assert.Equal(1, UV.PointerCount); #endif }
public static void NotNullUdp(IPEndPoint ep) { var u = new Udp(); Action<bool> cb = (_) => { }; string ipstr = ep.Address.ToString(); var ip = ep.Address; // constructor Assert.Throws<ArgumentNullException>(() => new Udp(null)); // bind Assert.Throws<ArgumentNullException>(() => u.Bind(null)); Assert.Throws<ArgumentNullException>(() => u.Bind(null as string, 0)); Assert.Throws<ArgumentNullException>(() => u.Bind(null as IPAddress, 0)); // receive Assert.Throws<ArgumentNullException>(() => u.Receive(null)); Assert.Throws<ArgumentNullException>(() => u.Receive(Encoding.ASCII, null)); Assert.Throws<ArgumentNullException>(() => u.Receive(null, (_, __) => { })); // send Assert.Throws<ArgumentNullException>(() => u.Send(null as IPEndPoint, new byte[] { })); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPEndPoint, new byte[] { }, 0)); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPEndPoint, new byte[] { }, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPEndPoint, new byte[] { }, 0, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ep, null as byte[])); Assert.Throws<ArgumentNullException>(() => u.Send(ep, null as byte[], 0)); Assert.Throws<ArgumentNullException>(() => u.Send(ep, null as byte[], cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ep, null as byte[], 0, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(null as string, 0, new byte[] { })); Assert.Throws<ArgumentNullException>(() => u.Send(null as string, 0, new byte[] { }, 0)); Assert.Throws<ArgumentNullException>(() => u.Send(null as string, 0, new byte[] { }, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(null as string, 0, new byte[] { }, 0, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ipstr, 0, null as byte[])); Assert.Throws<ArgumentNullException>(() => u.Send(ipstr, 0, null as byte[], 0)); Assert.Throws<ArgumentNullException>(() => u.Send(ipstr, 0, null as byte[], cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ipstr, 0, null as byte[], 0, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPAddress, 0, new byte[] { })); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPAddress, 0, new byte[] { }, 0)); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPAddress, 0, new byte[] { }, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(null as IPAddress, 0, new byte[] { }, 0, cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ip, 0, null as byte[])); Assert.Throws<ArgumentNullException>(() => u.Send(ip, 0, null as byte[], 0)); Assert.Throws<ArgumentNullException>(() => u.Send(ip, 0, null as byte[], cb)); Assert.Throws<ArgumentNullException>(() => u.Send(ip, 0, null as byte[], 0, cb)); u.Close(); Loop.Default.RunOnce(); }
public Client(string name, string hostIP) { this.name = name; this.hostIP = hostIP; this.players = new Dictionary<int, Player>(); this.boxes = new List<Box>(); this.udp = new Udp(CONNECT_PORT, OnReceive); this.udp.SetDestination(hostIP, Server.SERVER_PORT); this.isDisconnected = false; }
void TestCanSendHandles(string pipename, IPEndPoint ipep) { int count = 0; Loop.Default.Run(async () => { var handles = new Stack<Handle>(); var pipelistener = new IPCPipeListener(); pipelistener.Bind(pipename); pipelistener.Connection += () => { var client = pipelistener.Accept(); client.Resume(); client.HandleData += (handle, data) => { handles.Push(handle); count++; if (count == 3) { foreach (var h in handles) { h.Close(); } pipelistener.Close(); } }; }; pipelistener.Listen(); var pipe = new IPCPipe(); await pipe.ConnectAsync(pipename); var tcplistener = new TcpListener(); tcplistener.Bind(ipep); tcplistener.Connection += () => { var client = tcplistener.Accept(); pipe.Write(client, new byte[1], (ex) => { client.Close(); tcplistener.Close(); }); }; tcplistener.Listen(); var tcp = new Tcp(); await tcp.ConnectAsync(ipep); tcp.Write("HELLO WORLD"); var udp = new Udp(); udp.Bind(ipep); pipe.Write(udp, Encoding.Default.GetBytes("UDP"), (ex) => udp.Close()); pipe.Write(pipe, Encoding.Default.GetBytes("pipe"), (ex) => pipe.Close()); }); Assert.Equal(3, count); }
public void Disconnect() { if (!isDisconnected && null != udp) { isDisconnected = true; JObject json = new JObject(); json[Tag.COMMAND] = Cmd.DISCONNECT; json[Tag.ID] = id; udp.Send(json.ToString()); udp.Close(); udp = null; } }
private void OnStop() { Invalidater.Instance.Unregister(this); if (udp != null) { if (players.Count > 0) { JObject res = new JObject(); res[Tag.COMMAND] = Cmd.SERVER_CLOSED; Broadcast(res.ToString()); } players.Clear(); keys.Clear(); udp.Close(); udp = null; } }
private void OnStart() { udp = new Udp(SERVER_PORT, OnReceive); Invalidater.Instance.Register(this); }
public static void Run(IPEndPoint ep) { int close_cb_called = 0; int cl_send_cb_called = 0; int cl_recv_cb_called = 0; int sv_send_cb_called = 0; int sv_recv_cb_called = 0; Udp client = new Udp(); Udp server = new Udp(); server.Bind(ep); server.Receive(Encoding.ASCII, (rinfo, str) => { Assert.AreEqual(str, "PING"); sv_recv_cb_called++; server.Send(rinfo, Encoding.ASCII.GetBytes("PONG"), (s) => { sv_send_cb_called++; server.Close(() => { close_cb_called++; }); }); }); client.Send(ep, Encoding.ASCII.GetBytes("PING"), (s) => { cl_send_cb_called++; client.Receive(Encoding.ASCII, (rinfo, str) => { Assert.AreEqual(str, "PONG"); cl_recv_cb_called++; client.Close(() => { close_cb_called++; }); }); }); Assert.AreEqual(0, close_cb_called); Assert.AreEqual(0, cl_send_cb_called); Assert.AreEqual(0, cl_recv_cb_called); Assert.AreEqual(0, sv_send_cb_called); Assert.AreEqual(0, sv_recv_cb_called); Loop.Default.Run(); Assert.AreEqual(2, close_cb_called); Assert.AreEqual(1, cl_send_cb_called); Assert.AreEqual(1, cl_recv_cb_called); Assert.AreEqual(1, sv_send_cb_called); Assert.AreEqual(1, sv_recv_cb_called); #if DEBUG Assert.AreEqual(1, UV.PointerCount); #endif }
public void OnReceive(IPEndPoint endpoint, string msg) { JObject json = JObject.Parse(msg); int cmd = (int)json[Tag.COMMAND]; if (cmd == Cmd.CONNECT && (int)json[Tag.STATUS] == Status.SUCCESS) { int gamePort = (int)json[Tag.PORT]; id = (int)json[Tag.ID]; this.udp.Close(); this.udp = new Udp(gamePort, OnReceive); this.udp.SetDestination(hostIP, Server.SERVER_PORT); JArray jps = json[Tag.PLAYERS] as JArray; if (null != jps) { foreach (JObject jp in jps) { int _id = (int)jp[Tag.ID]; string ip = (string)jp[Tag.IP]; int port = (int)jp[Tag.PORT]; string name = (string)jp[Tag.NAME]; int tx = (int)jp[Tag.TX]; int ty = (int)jp[Tag.TY]; Player p = new Player(new IPEndPoint(IPAddress.Parse(ip), port), name, _id); p.position = new System.Drawing.Point(tx, ty); players[_id] = p; } } JArray jbs = json[Tag.BOXES] as JArray; if (null != jbs) { foreach (JObject jb in jbs) { int tx = (int)jb[Tag.TX]; int ty = (int)jb[Tag.TY]; Box box = new Box(); box.position = new System.Drawing.Point(tx, ty); boxes.Add(box); } } } else if (cmd == Cmd.ADD_PLAYER) { int _id = (int)json[Tag.ID]; string ip = (string)json[Tag.IP]; int port = (int)json[Tag.PORT]; string name = (string)json[Tag.NAME]; int tx = (int)json[Tag.TX]; int ty = (int)json[Tag.TY]; Player p = new Player(new IPEndPoint(IPAddress.Parse(ip), port), name, _id); p.position = new System.Drawing.Point(tx, ty); players[_id] = p; } else if (cmd == Cmd.DISCONNECT) { int _id = (int)json[Tag.ID]; players.Remove(_id); } else if (cmd == Cmd.SERVER_CLOSED) { Disconnect(); } else if (cmd == Cmd.UPDATE) { JArray jpos = json[Tag.POSITIONS] as JArray; foreach (JObject jp in jpos) { int _id = (int)jp[Tag.ID]; if (players.ContainsKey(_id)) { int tx = (int)jp[Tag.TX]; int ty = (int)jp[Tag.TY]; Player p = players[_id]; p.position.X = tx; p.position.Y = ty; } } } }