Cool Guy said:
Is it possible for one thread to perform a blocking read on a socket while
another thread performs a blocking write on it?
I'm about to start writing an IRC client and I'm considering having a
thread in which all the reading from the socket takes place, and another
thread in which all the writing to the socket takes place.
Is this thread-safe, etc.?
Well, I did a Google search and a Google Groups search, and it seems that
there are quite a few people who think this is okay (in Winsock, at least).
Also, the program listed at the end of this post works as expected.
So I'm going to do this and cross my fingers.
Program:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
class Test {
static Socket socket;
[STAThread]
static void Main(string[] args) {
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(new IPEndPoint(Dns.Resolve("google.com").AddressList[0],
80));
new Thread(new ThreadStart(Receive)).Start();
Thread.Sleep(1000);
string httpRequest = "GET /non-existant-URI HTTP/1.0\r\n\r\n";
socket.Send(Encoding.ASCII.GetBytes(httpRequest));
Console.Write("Request sent.\n\n");
Console.Read();
}
static void Receive() {
Console.Write("Ready to receive.\n\n");
byte[] buffer = new byte[99999];
socket.Receive(buffer);
Console.WriteLine(
"Reponse received!\n\n" +
"First few characters:\n\n" +
"{0}",
Encoding.ASCII.GetString(buffer).Substring(0, 100));
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}