suggested use Asynchronous Programming(Async Task)
Server:
int connectCount = 0; Console.WriteLine("wait for conncet..."); Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress iPAddress = new IPAddress(new byte[] {192,168,2,103 }); IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788); tcpServer.Bind(endPoint); tcpServer.Listen(100); var client= tcpServer.Accept(); Console.WriteLine($"conncet:{++connectCount}{client.AddressFamily.ToString()}"); byte[] data = new byte[1024]; int len= client.Receive(data); Console.WriteLine(Encoding.UTF8.GetString(data,0,len)); string ServerMessage = "Server Send Message to Client"; Console.WriteLine($"Send:{ServerMessage}"); client.Send(Encoding.UTF8.GetBytes(ServerMessage)); client.Close(); tcpServer.Close(); Console.ReadLine();
Client:
using System.Net; using System.Net.Sockets; using System.Text; Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 2, 103 });//IP IPEndPoint endPoint = new IPEndPoint(iPAddress, 7788);//port tcpClient.Connect(endPoint); //connect Console.WriteLine("connect.."); string sendMessage = "line"; Console.WriteLine($"send:{sendMessage}..."); tcpClient.Send(Encoding.UTF8.GetBytes(sendMessage));//send byte[] data = new byte[1024]; int len = tcpClient.Receive(data); Console.WriteLine($"Server:{Encoding.UTF8.GetString(data, 0, len)}");