Synchronous and asynchronous Connect/Send/Receive methods can be mixed. But you got to take care that you don't do 2 calls at the same time, like Connecting with BeginnConnect and then directly trying to use Receive.
You can use the IAsyncResult to determine if the asynchronous call has finished.
This example works without problems, using a tcp echo server on the same pc:
Socket myAsyncConnectSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
myAsyncConnectSocket.ReceiveTimeout = 10;
myAsyncConnectSocket.SendTimeout = 10;
int connectTimeout = 10;
var asyncResult = myAsyncConnectSocket.BeginConnect(
new IPEndPoint(IPAddress.Loopback, 57005), null, null);
bool timeOut = true;
if (asyncResult.AsyncWaitHandle.WaitOne(connectTimeout))
{
timeOut = false;
Console.WriteLine("Async Connected");
try
{
myAsyncConnectSocket.Send(Encoding.ASCII.GetBytes("Test 1 2 3"));
Console.WriteLine("Sent");
byte[] buffer = new byte[128];
myAsyncConnectSocket.Receive(buffer);
Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(buffer));
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.TimedOut) timeOut = true;
else throw;
}
}
Console.WriteLine("Timeout occured: {0}", timeOut);
Take a special look into asyncResult.AsyncWaitHandle.WaitOne()
as it blocks the current thread until the asynchronous connect is finished, you have to manage this connectionstate yourself if you want to connect/send/receive on different threads.