The server can only register each packet type once. Therefore, on serverside we have to use the “RegisterStaticPacketHandler” method. That will map a packettype directly to the given delegate. In the following example we start to listen to a “CalculationRequest” after a connection has been established.
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 |
public void Demo() { //1. Start listen on a port serverConnectionContainer = ConnectionFactory.CreateServerConnectionContainer(1234, false); //2. Apply optional settings. #region Optional settings serverConnectionContainer.ConnectionLost += (a, b, c) => Console.WriteLine($"{serverConnectionContainer.Count} {b.ToString()} Connection lost {a.IPRemoteEndPoint.Port}. Reason {c.ToString()}"); serverConnectionContainer.ConnectionEstablished += connectionEstablished; serverConnectionContainer.AllowBluetoothConnections = true; serverConnectionContainer.AllowUDPConnections = true; serverConnectionContainer.UDPConnectionLimit = 2; #endregion Optional settings //Call start here, because we had to enable the bluetooth property at first. serverConnectionContainer.Start(); } /// <summary> /// We got a connection. /// </summary> /// <param name="connection">The connection we got. (TCP or UDP)</param> private void connectionEstablished(Connection connection, ConnectionType type) { Console.WriteLine($"{serverConnectionContainer.Count} {connection.GetType()} connected on port {connection.IPRemoteEndPoint.Port}"); //3. Register packet listeners. connection.RegisterStaticPacketHandler<CalculationRequest>(calculationReceived); } /// <summary> /// If the client sends us a calculation request, it will end up here. /// </summary> /// <param name="packet">The calculation packet.</param> /// <param name="connection">The connection who was responsible for the transmission.</param> private static void calculationReceived(CalculationRequest packet, Connection connection) { //4. Handle incoming packets. connection.Send(new CalculationResponse(packet.X + packet.Y, packet)); } |
connection.RegisterStaticPacketHandler registers the generic <CalculationRequest> to the delegate “calculationReceived”. If the client sends a “CalculationRequest” the server is going to receive that packet directly in the “calculationReceived” method. Because we directly receive a “CalculationRequest” we don’t need any cast.
Du musst angemeldet sein, um kommentieren zu können.