public void SingleStep() { byte[] data = transport.Receive(); if (data != null) { byte command = data[0]; float firstNum = BitConverter.ToSingle(data, 1); float secondNum = BitConverter.ToSingle(data, 5); Result = commandsTable[command](firstNum, secondNum); Packet response = new Packet(0, Result); byte[] returnData = response.GetData(); transport.Send(returnData); } }
private void RecvData(IAsyncResult asyncResult) { try { byte[] data; Packet recvData = new Packet(this.buffer); IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0); EndPoint epSender = (EndPoint)clients; serverSocket.EndReceiveFrom(asyncResult, ref epSender); Console.WriteLine(recvData.Name + " " + recvData.Message); Packet sendData = new Packet { PacketType = recvData.PacketType, Name = recvData.Name }; switch (recvData.PacketType) { case PacketType.Message: sendData.Message = $"{recvData.Name}: {recvData.Message}"; Console.WriteLine(sendData.Message); break; case PacketType.Login: clientList.Add(new Client { EndPoint = epSender, Name = recvData.Name }); sendData.Message = $"{recvData.Name} has connected!"; break; case PacketType.Logout: foreach (Client client in clientList) { if (client.EndPoint.Equals(epSender)) { this.clientList.Remove(client); break; } } sendData.Message = $"{recvData.Name} has disconnected!"; break; } data = sendData.GetData(); foreach (Client client in clientList) { if (client.EndPoint != epSender) //broadcast message to a { serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, client.EndPoint, new AsyncCallback(this.SendData), client.EndPoint); } else { if (sendData.PacketType == PacketType.Login) // send Ack to client { var ackData = new Packet { Message = "You have sucessfully connected to the server", Name = "Server", PacketType = PacketType.Null }.GetData(); serverSocket.BeginSendTo(ackData, 0, ackData.Length, SocketFlags.None, client.EndPoint, new AsyncCallback(this.SendData), client.EndPoint); } } } serverSocket.BeginReceiveFrom(this.buffer, 0, this.buffer.Length, SocketFlags.None, ref epSender, new AsyncCallback(RecvData), epSender); Console.WriteLine("sending: " + sendData.Message); } catch (Exception excpt) { Console.WriteLine(excpt); } }