You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB
C#

using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Connect("127.0.0.1", "Hello I'm Client 1...");
}).Start();
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Connect("127.0.0.1", "Hello I'm Client 2...");
}).Start();
Console.ReadLine();
}
private static void Connect(string server, string message)
{
try
{
Int32 port = 3000;
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
int count = 0;
while (count++ < 3)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine($"Sent: {message}");
data = new Byte[256];
string response = string.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine($"Received: {response}");
Thread.Sleep(2000);
}
stream.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine($"Exception: {e}");
}
Console.Read();
}
}