Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Threading.Tasks;
- using Google.Protobuf;
- using Google.Protobuf.Examples.AddressBook;
- namespace App
- {
- public class TcpServer
- {
- private readonly TcpListener listener;
- private readonly List<TcpClient> pool;
- public TcpServer(IPAddress ip, int port)
- {
- if (ip == null)
- throw new NullReferenceException();
- if (port < 0)
- throw new Exception();
- listener = new TcpListener(ip, port);
- pool = new List<TcpClient>();
- }
- public async Task<TcpClient> Start(int? backlog = null)
- {
- if (backlog.HasValue)
- listener.Start(backlog.Value);
- else
- listener.Start();
- Console.WriteLine("Server started. Listening to the TCP clients...");
- return await listener.AcceptTcpClientAsync();
- }
- public async Task HandleNewConnection()
- {
- pool.Add(await Start());
- Console.WriteLine("Client has been connected. Waiting for the input data...");
- Task.Factory.StartNew(async() => await HandleInputData(pool[pool.Count - 1]));
- await HandleNewConnection();
- }
- private async Task HandleInputData(TcpClient client)
- {
- var data = new byte[4096];
- var cts = new CancellationTokenSource();
- var john = new Person
- {
- Id = 1234,
- Name = "John Doe",
- Email = "jdoe@example.com",
- Phones = { new Person.Types.PhoneNumber { Number = "555-4321", Type = Person.Types.PhoneType.Home } }
- };
- var ms = new MemoryStream();
- var os = new CodedOutputStream(ms);
- john.WriteTo(os);
- os.Flush();
- var rawData = ms.ToArray();
- var str = Encoding.UTF8.GetString(rawData);
- var networkStream = client.GetStream();
- var hwText = Encoding.UTF8.GetBytes(Convert.ToBase64String(rawData));
- await networkStream.WriteAsync(hwText, 0, hwText.Length, cts.Token);
- var bytesRead = await networkStream.ReadAsync(data, 0, data.Length, cts.Token);
- if (bytesRead > 0)
- {
- var text = Encoding.UTF8.GetString(data, 0, bytesRead);
- Console.WriteLine($"Response is: {text}");
- }
- await HandleInputData(client);
- }
- }
- class Program
- {
- private const string ip = "127.0.0.1";
- private const int port = 8080;
- [MTAThread]
- public static void Main()
- {
- Task.Factory.StartNew(async() =>
- {
- var server = new TcpServer(IPAddress.Parse(ip), port);
- await server.HandleNewConnection();
- });
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement