public static void ListenerProto(string ip, int port) { TcpListener server = null; try { Console.WriteLine();
IPAddress localAddr = IPAddress.Parse(ip);
// TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port);
// Start listening for client requests. server.Start();
// Buffer for reading data byte[] bytes = new byte[10000];
// Enter the listening loop. while (true) { Console.WriteLine("Waiting for a connection... ");
// Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!");
// Get a stream object for reading and writing NetworkStream stream = client.GetStream();
CodedInputStream cod = new CodedInputStream(stream); var tcpMessage = TCPMessage.Parser.ParseFrom(cod);
// Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine($"SocketException: {e}"); } finally { // Stop listening for new clients. server?.Stop(); } }public static void ClientProto(string ipServer, int port, TCPMessage message) { try { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, port // combination. TcpClient client = new TcpClient(ipServer, port);
//Create stream var stream = client.GetStream();
//Create Coded output stream to send data over the tcp client CodedOutputStream cod = new CodedOutputStream(stream);
// Send the message to the connected TcpServer. //message.WriteTo(stream); var calculateSize = message.CalculateSize();
message.WriteTo(cod);
//Write message in tb Console.WriteLine($"Sent: {message}");
// Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException e) { Console.WriteLine($"ArgumentNullException: {e}"); } catch (SocketException e) { Console.WriteLine($"SocketException: {e}"); } }syntax = "proto3";
message TCPMessage { enum Type { Add = 0; Remove = 1; Select = 2; Update = 3; } message Parameter { string name = 1; string value = 2; } message EmbeddedMessage { string id = 1; Type type = 2; repeated Parameter parameters = 3; } Type commande = 1; EmbeddedMessage type = 2;}