networking-demo

networking-demo.git
git clone git://git.lenczewski.org/networking-demo.git
Log | Files | Refs | README

Program.cs (1957B)


      1 using System;
      2 using System.Net;
      3 
      4 using NetworkingDemo.Packets;
      5 
      6 namespace NetworkingDemo {
      7 	internal class Program {
      8 		// hosting the server at 127.0.0.1:12345 for sake of demo
      9 		static readonly IPAddress Addr = IPAddress.Loopback;
     10 		const int Port = 12345;
     11 
     12 		static void Main(string[] args) {
     13 			// server demo, wait for clients and handle them
     14 			Server server = new Server(Addr, Port);
     15 
     16 			// setup all server-side packet handlers
     17 			server.On(PacketType.Ping, (buffer, conn) => {
     18 				PingPacket packet = new PingPacket();
     19 
     20 				if (!packet.TryDeserializeFrom(buffer)) {
     21 					return ConnectionResult.CloseConnection;
     22 				}
     23 
     24 				conn.Send(new PongPacket(packet.Value));
     25 
     26 				return ConnectionResult.ReceivePackets;
     27 			});
     28 
     29 			// start listening for incoming client connections
     30 			server.Start();
     31 
     32 
     33 			// client demo, send and receive multiple packets
     34 			Client client = new Client();
     35 			Connection connection = client.ConnectTo(Addr, Port);
     36 
     37 			// setup all client-side packet handlers
     38 			connection.On(PacketType.Welcome, (buffer, conn) => {
     39 				WelcomePacket packet = new WelcomePacket();
     40 
     41 				if (!packet.TryDeserializeFrom(buffer)) {
     42 					return ConnectionResult.CloseConnection;
     43 				}
     44 
     45 				Console.WriteLine($"[server->client] Welcome: {packet.Msg}");
     46 
     47 				return ConnectionResult.ReceivePackets;
     48 			});
     49 
     50 			connection.On(PacketType.Pong, OnPongPacket);
     51 
     52 			// start listening for incoming packets
     53 			connection.BeginRecv();
     54 
     55 			for (int i = 0; i < 10; i++) {
     56 				Console.WriteLine($"[client->server] Ping: {i}");
     57 				connection.Send(new PingPacket(i));
     58 			}
     59 
     60 
     61 			// wait for demo to end
     62 			Console.ReadLine();
     63 		}
     64 
     65 		static ConnectionResult OnPongPacket(Memory<byte> buffer, Connection conn) {
     66 			PongPacket packet = new PongPacket();
     67 
     68 			if (!packet.TryDeserializeFrom(buffer)) {
     69 				return ConnectionResult.CloseConnection;
     70 			}
     71 
     72 			Console.WriteLine($"[server->client] Pong: {packet.Value}");
     73 
     74 			return ConnectionResult.ReceivePackets;
     75 		}
     76 	}
     77 }