Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Newtonsoft.Json;
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading.Tasks;
- namespace ConsoleApp1
- {
- class Program
- {
- class A
- {
- public int X { get; set; }
- public string Y { get; set; }
- }
- static async Task ReceiveLoop(TcpClient client)
- {
- using (client)
- using (var stream = client.GetStream())
- {
- while (true)
- {
- object obj = await stream.ReadObjectAsync();
- if (obj == null)
- break;
- Console.WriteLine($"server received object: {obj.GetType()} {JsonConvert.SerializeObject(obj)}");
- await stream.WriteObjectAsync("received success");
- }
- Console.WriteLine("connection closed");
- }
- }
- static async Task Server(IPAddress addr, int port)
- {
- var listener = new TcpListener(addr, port);
- listener.Start();
- while (true)
- ReceiveLoop(await listener.AcceptTcpClientAsync());
- }
- static async Task Client(string addr, int port)
- {
- using (var client = new TcpClient())
- {
- await client.ConnectAsync(addr, port);
- using (var stream = client.GetStream())
- {
- await stream.WriteObjectAsync(new A() { X = 123, Y = "abc" });
- var obj = await stream.ReadObjectAsync();
- Console.WriteLine(obj);
- }
- }
- }
- static void Main(string[] args)
- {
- Task.Run(() => Server(IPAddress.Any, 8888));
- Task.Run(() => Client("127.0.0.1", 8888));
- Task.Run(() => Client("127.0.0.1", 8888));
- Console.ReadLine();
- }
- }
- }
Add Comment
Please, Sign In to add comment