My program:
I create 2 threads:Thread 1 with a listen socket,and thread 2 do somethings.
But thread 1 blocks program and i can not start thread 2 until listen socket on thread 1 receives data.
But i need 2 threads run at the same time,and don`t need to keep in sync between 2 threads.(but still in same program).
How to do it???
My code like this:
Thread thread1 = new Thread(new ThreadStart(a.thread1));
Thread thread2 = new Thread(new ThreadStart(b.thread2));
try
{
thread1.Start();
thread2.Start();
thread1.Join(); // Join both threads with no timeout
// Run both until done.
thread2.Join();
}
I have just recently had this self same issue and resolved it like this:
private static void StartServers()
{
for (int i = Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortStart"));
i <= Convert.ToInt32(ConfigurationManager.AppSettings.Get("PortEnd"));
i++)
{
var localAddr = IPAddress.Parse(ConfigurationManager.AppSettings.Get("IpAddress"));
var server = new TcpListener(localAddr, i);
Servers.Add(server);
server.Start();
StartAccept(server);
}
}
private static void StartAccept(TcpListener server)
{
server.BeginAcceptTcpClient(OnAccept, server);
}
private static void OnAccept(IAsyncResult res)
{
var client = new TcpClient();
try
{
Console.ForegroundColor = Console.ForegroundColor == ConsoleColor.Red
? ConsoleColor.Green
: ConsoleColor.White;
var server = (TcpListener) res.AsyncState;
StartAccept(server);
client = server.EndAcceptTcpClient(res);
Console.WriteLine("Connected!\n");
var bytes = new byte[512];
// Get a stream object for reading and writing
var stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
var data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0} \n", data);
// Process the data sent by the client.
data = InterpretMessage(data);
var msg = Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0} \n", data);
}
}
catch (Exception exception)
{
Console.ForegroundColor = ConsoleColor.Red;
client.Close();
Console.WriteLine(exception.Message);
}
}
Basically what this does is creates an asynchronous receiving system in which you can have multiple servers listening to multiple ports simultaneously. Bearing in mind that you can only ever have one listener per port.
In your example, you can simply call the StartServers method and then directly afterwards, continue with whatever your application is doing.
In order for this to work for a single server on a single port, merely remove the looping in StartServers and configure 1 TcpListener and start it up.