public static void Receive(TcpClient connection, BinaryReader reader, PacketProtocol packetProtocol) { var bufferSize = connection.Available; var buffer = reader.ReadBytes(bufferSize); packetProtocol.DataReceived(buffer); }
public void Send_Message_CallsBeginSend() { MessageType messageType = MessageType.Init; byte[] message = Encoding.ASCII.GetBytes("test message"); var mock = new Mock <ISocketConnection>(); mock.Setup(x => x.Connected).Returns(true); byte[] expectedMessage = PacketProtocol <MessageType> .WrapMessage(messageType, message); byte[] receivedMessage = null; mock.Setup(x => x.BeginSend( It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <SocketFlags>(), It.IsAny <AsyncCallback>(), It.IsAny <object>())) .Callback <byte[], int, int, SocketFlags, AsyncCallback, object>((data, offset, size, socketFlags, asyncCallback, state) => { receivedMessage = data; }); SocketConnectionController <MessageType> controller = new SocketConnectionController <MessageType>(mock.Object, 1024); controller.Start(); controller.Send(messageType, message); Assert.AreEqual(expectedMessage, receivedMessage); }
// -------------------- SEND -------------------- \\ public void Send(TMessageType messageType, byte[] message) { if (!IsConnected) { throw new Exception("SocketConnectionController is not connected"); } if (_isDisposed) { throw new ObjectDisposedException("SocketConnectionController has been disposed"); } byte[] data = PacketProtocol <TMessageType> .WrapMessage(messageType, message); // Log the incoming message. Ignoring often occurring types. /*if (messageType != MessageType.Animation_Request) * { * Console.WriteLine($"[OUT] [{messageType}] length:{message.Length}"); * }*/ // Begin sending the data to the remote device. try { _socket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), _socket); } catch (SocketException e) { OnDisconnect(e); } }
//////////////// public override void HandlePacket(BinaryReader reader, int player_who) { try { int protocol_code = reader.ReadInt32(); if (Main.netMode == 1) { if (protocol_code >= 0) { PacketProtocol.HandlePacketOnClient(protocol_code, reader, player_who); } else { Utilities.Network.OldPacketProtocol.HandlePacketOnClient(protocol_code, reader, player_who); } } else if (Main.netMode == 2) { if (protocol_code >= 0) { PacketProtocol.HandlePacketOnServer(protocol_code, reader, player_who); } else { Utilities.Network.OldPacketProtocol.HandlePacketOnServer(protocol_code, reader, player_who); } } } catch (Exception e) { DebugHelpers.LogHelpers.Log("(Mod Helpers) HandlePacket - " + e.ToString()); } }
public void Send_message_SendsMessage() { // Establish the local endpoint for the socket. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 20055); // Create a server Socket server = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.Bind(localEndPoint); server.Listen(2); // Create a SocketConnectionController SocketConnection socket = new SocketConnection(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(localEndPoint); SocketConnectionController <MessageType> socketConnectionController = new SocketConnectionController <MessageType>(socket, 1024); socketConnectionController.Start(); Socket server_receiver = server.Accept(); Thread.Sleep(1000); byte[] message = Encoding.ASCII.GetBytes("ThisIsAMessage"); byte[] expectedData = PacketProtocol <MessageType> .WrapMessage(MessageType.Standard, message); socketConnectionController.Send(MessageType.Standard, message); byte[] receiveBuffer = new byte[expectedData.Length]; server_receiver.Receive(receiveBuffer); Assert.AreEqual(expectedData, receiveBuffer); }
private void ClientSocket_ConnectCompleted(object sender, TcpCompletedEventArgs e) { if (!e.Error) { Console.WriteLine($"Connected to {(IPEndPoint)e.Data}"); PacketProtocol = new PacketProtocol(ClientSocket); PacketProtocol.PacketArrived += PacketProtocol_PacketArrived; PacketProtocol.Start(); Console.WriteLine("Sending client info..."); PacketProtocol.SendPacket(ClientSocket, new Packet { Content = World.LocalPlayer, Type = PacketType.PLAYER_INFO }); World.AddPlayer(World.LocalPlayer); ConnectedToServer?.Invoke(ClientSocket.RemoteEndPoint.ToString(), World.LocalPlayer.Name); _connected = true; } else { CriticalErrorOccured($"Произошла критическая ошибка!\n{((Exception)e.Data).Message}"); } }
private void ReceiveCallback(IAsyncResult ar) { EndPoint source = new IPEndPoint(0, 0); int bytesRead = 0; try { bytesRead = _socket.EndReceiveFrom(ar, ref source); } catch (SocketException) { return; } // Parse the message if (source.Equals(_targetEndPoint) && bytesRead > 0) { try { byte[] b = (byte[])ar.AsyncState; _packetProtocol.DataReceived(b, bytesRead); } catch (ProtocolViolationException e) { _packetProtocol.MessageArrived = null; _packetProtocol = new PacketProtocol <TMessageType>(_bufferSize); _packetProtocol.MessageArrived = (MessageType, data) => OnMessageReceived(MessageType, data); } } // Start receiving more data StartReceive(); }
public void DataReceived_FullMessage_ReturnsCorrectMessage() { MessageType expectedMessageType = MessageType.Init; byte[] expectedBytes = new byte[] { 1, 2, 3, 4 }; byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes); MessageType receivedMessageType = MessageType.Unknown; byte[] receivedBytes = null; PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100); packetProtocol.MessageArrived += (type, bytes) => { receivedMessageType = type; receivedBytes = bytes; }; packetProtocol.DataReceived(message, message.Length); Assert.AreEqual(expectedMessageType, receivedMessageType); Assert.AreEqual(expectedBytes, receivedBytes); }
public void DataReceived_LengthShorterThanBuffer_OnlyReadsTheLength() { MessageType expectedMessageType = MessageType.Init; byte[] expectedBytes = new byte[] { 1, 2, 3, 4 }; byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes); // Add bytes the package protocol should not read. byte[] tooLongMessage = message.Concat(new byte[] { 9, 8, 7 }).ToArray(); MessageType receivedMessageType = MessageType.Unknown; byte[] receivedBytes = null; PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100); packetProtocol.MessageArrived += (type, bytes) => { receivedMessageType = type; receivedBytes = bytes; }; packetProtocol.DataReceived(tooLongMessage, message.Length); Assert.AreEqual(expectedMessageType, receivedMessageType); Assert.AreEqual(expectedBytes, receivedBytes); }
public virtual void WriteData(BinaryWriter writer, PacketProtocol _) { string json_str = JsonConvert.SerializeObject(this); var data = Encoding.ASCII.GetBytes(json_str); writer.Write((int)data.Length); writer.Write(data); }
public void Start() { _packetProtocol = new PacketProtocol <TMessageType>(_bufferSize); _packetProtocol.MessageArrived = (MessageType, data) => OnMessageReceived(MessageType, data); IsConnected = true; StartReceive(); }
public void SendAsync(byte[] data) { SendData sendData = new SendData() { Data = data }; PacketProtocol.SendAsync(sendData); }
public PacketInfo(string packetSourceMAC, string packetDestMAC, string sourceIP, string destIP, PacketProtocol packetProtocol, string packetPort, string packetSize, DateTime packetTime) { sourceMAC = packetSourceMAC; destMAC = packetDestMAC; sourceAddress = sourceIP; destAddress = destIP; protocol = packetProtocol; localPort = packetPort; size = packetSize; time = packetTime; }
public static void EndPrompts() { var mymod = HamstarHelpersMod.Instance; mymod.Config.IsServerPromptingForBrowser = false; mymod.ConfigJson.SaveFile(); if (Main.netMode == 2) { PacketProtocol.QuickSendToClient <ModSettingsProtocol>(-1, -1); } }
public static void QuickSendRequest <T>(int to_who, int ignore_who) where T : PacketProtocol, new() { if (Main.netMode == 1) { PacketProtocol.QuickRequestToServer <T>(); } else if (Main.netMode == 2) { PacketProtocol.QuickRequestToClient <T>(to_who, ignore_who); } }
internal void BroadcastPacket(Packet packet, Guid excludeGuid) { foreach (KeyValuePair <GameTcpServerConnection, ClientContext> client in clients) { if (client.Value.Player.Guid == excludeGuid) { continue; } PacketProtocol.SendPacket(client.Key, packet); } }
public void OnEnterWorldClient(HamstarHelpersMod mymod, Player player) { if (this.HasUID) { PacketProtocol.QuickSendToServer <PlayerIdProtocol>(); } PlayerDataProtocol.SyncToEveryone(this.PermaBuffsById, this.HasBuffIds, this.EquipSlotsToItemTypes); PacketProtocol.QuickRequestToServer <ModSettingsProtocol>(); PacketProtocol.QuickRequestToServer <WorldDataProtocol>(); mymod.ControlPanel.LoadModListAsync(); }
public async void SendAsync(object data) { try { var bytes = PacketProtocol.WrapMessage(netSettings.serializer.Invoke(data)); await stream.WriteAsync(bytes, 0, bytes.Length); } catch (Exception ex) { OnDisconnected?.Invoke(null, new DisconnectEventArgs { Exception = ex }); } }
public void DataReceived_PackageTooLong_ThrowsProtocolViolationException() { MessageType expectedMessageType = MessageType.Init; byte[] expectedBytes = new byte[] { 1, 2, 3, 4 }; byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes); // Add bytes the package protocol should not read. PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(10); Assert.Throws <ProtocolViolationException>(() => packetProtocol.DataReceived(message, message.Length)); }
public void StartReceiveAsync() { try { bool willRaiseEvent = ConnectSocket.ReceiveAsync(ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { PacketProtocol.ReceiveComplate(null, ReceiveEventArgs); } } catch (Exception e) { loger.Fatal(e); } }
public void ReceiveCallback_Message_InvokesMessageArrived() { // The receive callback is private. We have to chain the receive via the start function. MessageType messageType = MessageType.Init; byte[] message = Encoding.ASCII.GetBytes("test message"); var mock = new Mock <ISocketConnection>(); mock.Setup(x => x.Connected).Returns(true); byte[] dataToSend = PacketProtocol <MessageType> .WrapMessage(messageType, message); var asyncStateMock = new Mock <IAsyncResult>(); asyncStateMock.Setup(x => x.AsyncState).Returns(dataToSend); bool beginReceiveHasBeenInvoked = false; mock.Setup(x => x.BeginReceive( It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <SocketFlags>(), It.IsAny <AsyncCallback>(), It.IsAny <object>())) .Callback <byte[], int, int, SocketFlags, AsyncCallback, object>((data, offset, size, socketFlags, asyncCallback, state) => { if (!beginReceiveHasBeenInvoked) { beginReceiveHasBeenInvoked = true; // Prevent endless loop asyncCallback.Invoke(asyncStateMock.Object); // calls ReceiveCallBack } }); bool endSendCalled = false; mock.Setup(x => x.EndReceive(It.IsAny <IAsyncResult>())).Returns(dataToSend.Length).Callback(() => endSendCalled = true); SocketConnectionController <MessageType> controller = new SocketConnectionController <MessageType>(mock.Object, 1024); MessageReceivedEventArgs <MessageType> messageReceivedEventArgs = null; controller.MessageReceived += (sender, args) => { messageReceivedEventArgs = args; }; controller.Start(); Assert.IsTrue(endSendCalled); Assert.AreEqual(messageType, messageReceivedEventArgs.MessageType); Assert.AreEqual(message, messageReceivedEventArgs.Message); }
public void DataReceived_MessageSplitInMultiplePackages_ReturnsCorrectMessage() { MessageType expectedMessageType = MessageType.Init; byte[] expectedBytes = new byte[] { 1, 2, 3, 4 }; byte[] message = PacketProtocol <MessageType> .WrapMessage(expectedMessageType, expectedBytes); Assert.AreEqual(12, message.Length, "This test assumes the message length is 12"); byte[] messagePackage1 = { message[0], message[1], message[2] }; byte[] messagePackage2 = { message[3], message[4], message[5] }; byte[] messagePackage3 = { message[6], message[7], message[8] }; byte[] messagePackage4 = { message[9], message[10], message[11], }; MessageType receivedMessageType = MessageType.Unknown; byte[] receivedBytes = null; PacketProtocol <MessageType> packetProtocol = new PacketProtocol <MessageType>(100); packetProtocol.MessageArrived += (type, bytes) => { receivedMessageType = type; receivedBytes = bytes; }; packetProtocol.DataReceived(messagePackage1, messagePackage1.Length); Assert.AreEqual(MessageType.Unknown, receivedMessageType); packetProtocol.DataReceived(messagePackage2, messagePackage2.Length); Assert.AreEqual(MessageType.Unknown, receivedMessageType); packetProtocol.DataReceived(messagePackage3, messagePackage3.Length); Assert.AreEqual(MessageType.Unknown, receivedMessageType); packetProtocol.DataReceived(messagePackage4, messagePackage4.Length); Assert.AreEqual(expectedMessageType, receivedMessageType); Assert.AreEqual(expectedBytes, receivedBytes); }
private void SendComplate(object sender, SocketAsyncEventArgs sendEventArgs) { if (sendEventArgs.SocketError == SocketError.Success) { if (ConnectSocket != null) { PacketProtocol.SendProcess();//继续发送 } } else { lock (closeLock) { DisConnect(); } } }
private void ClientSocket_ShutdownCompleted(object sender, TcpCompletedEventArgs e) { Console.WriteLine("Disconnected from server."); PacketProtocol.PacketArrived -= PacketProtocol_PacketArrived; ClientSocket.ConnectCompleted -= ClientSocket_ConnectCompleted; ClientSocket.ShutdownCompleted -= ClientSocket_ShutdownCompleted; ClientSocket.Close(); ClientSocket = null; PacketProtocol = null; _connected = false; this.DisconnectedFromServer(); }
//////////////// public override void PostSetupContent() { this.OldPacketProtocols = Utilities.Network.OldPacketProtocol.GetProtocols(); this.PacketProtocols = PacketProtocol.GetProtocols(); this.Promises.OnPostSetupContent(); this.MenuUIMngr.OnPostSetupContent(); this.ModMetaDataManager.OnPostSetupContent(); if (!Main.dedServ) { UIControlPanel.OnPostSetupContent(this); } this.HasSetupContent = true; this.CheckAndProcessLoadFinish(); }
public void PreUpdateClient(HamstarHelpersMod mymod, Player player) { this.PreUpdatePlayer(mymod, player); if (player.whoAmI == Main.myPlayer) // Current player { var myworld = mymod.GetModWorld <HamstarHelpersWorld>(); myworld.WorldLogic.PreUpdateClient(mymod); } // Update ping every 15 seconds if (mymod.Config.IsServerGaugingAveragePing && this.TestPing++ > (60 * 15)) { PacketProtocol.QuickSendToServer <PingProtocol>(); this.TestPing = 0; } }
// -------------------- Receive -------------------- \\ private void ReceiveCallback(IAsyncResult ar) { // Read incoming data from the client. if (_isDisposed) { Console.WriteLine($"Ignored incoming message as this object is disposed."); return; } int bytesRead = 0; try { bytesRead = _socket.EndReceive(ar); } catch (SocketException e) { OnDisconnect(e); return; } if (bytesRead > 0) { // Parse the message lock (_parsingMessageLock) { try { byte[] b = (byte[])ar.AsyncState; _packetProtocol.DataReceived(b, bytesRead); } catch (ProtocolViolationException e) { Console.WriteLine("Failed to receive data. Package protocol violation. \n" + e.ToString()); _packetProtocol.MessageArrived = null; _packetProtocol.KeepAliveArrived = null; _packetProtocol = new PacketProtocol <TMessageType>(_bufferSize); _packetProtocol.MessageArrived = (MessageType, data) => OnMessageReceived(MessageType, data); } } // Start receiving more data byte[] buffer = new byte[_bufferSize]; _socket.BeginReceive(buffer, 0, _bufferSize, 0, new AsyncCallback(ReceiveCallback), buffer); } }
public void Send(TMessageType messageType, byte[] message) { if (_isDisposed) { throw new ObjectDisposedException("SocketConnectionController has been disposed"); } byte[] data = PacketProtocol <TMessageType> .WrapMessage(messageType, message); // Begin sending the data to the remote device. try { _socket.BeginSendTo(data, 0, data.Length, 0, _targetEndPoint, SendCallback, data); } catch (SocketException e) { } }
/// <summary> /// Sends message to remote client. /// </summary> /// <param name="client">Remote client socket object</param> /// <param name="data">Message to send</param> private static void Send(Socket client, Message data) { try { // convert message into byte array and wrap it for network transport: var serializedMsg = Message.Serialize(data); byte[] byteData = PacketProtocol.WrapMessage(serializedMsg); Debug.Log(String.Format("\t...almost send {0} bytes [{1}]", byteData.Length, data.Code));//----------- // Begin sending the data to the remote device: client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } catch (Exception ex) { Debug.Log(ex.ToString()); } }
private void KeepAliveCallback(object sender, ElapsedEventArgs elapsedEventArgs) { if (!IsConnected || _isDisposed) { return; } try { byte[] keepAliveBytes = PacketProtocol <TMessageType> .WrapKeepaliveMessage(); _socket.BeginSend(keepAliveBytes, 0, keepAliveBytes.Length, 0, new AsyncCallback(SendCallback), _socket); } catch (SocketException e) { OnDisconnect(e); } }