private void ConnectFunction(IAsyncResult ar) { client.EndConnect(ar); networkStream = client.GetStream(); TrueMessage trueMessageToServer = new TrueMessage { Command = Command.StudentConnect, Login = login }; byte[] dataConnectRequest; IFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, trueMessageToServer); dataConnectRequest = stream.ToArray(); } networkStream.BeginWrite(dataConnectRequest, 0, dataConnectRequest.Length, new AsyncCallback(ConnectRequest), null); }
private void ConnectCallBack(IAsyncResult result) { try { clientScocket.EndConnect(result); if (clientScocket.Connected == false) { Console.WriteLine("Server does not allow our connection."); return; } else { Console.WriteLine("Succesfully connected to the server!"); } } catch (Exception) { Console.WriteLine("Cannot connect to the server!");; } }
static void Main(string[] args) { if (args != null && args.Length > 0) { _UseKeepalives = args.Any(a => a.Equals("--keepalive")); } _Client = new TcpClient(); _Token = _TokenSource.Token; if (_UseKeepalives) { Console.WriteLine("Enabling TCP keepalives"); SetTcpKeepalives(); } else { Console.WriteLine("TCP keepalives disabled"); } IAsyncResult ar = _Client.BeginConnect("127.0.0.1", 9000, null, null); WaitHandle wh = ar.AsyncWaitHandle; if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { _Client.Close(); throw new TimeoutException(); } _Client.EndConnect(ar); _NetworkStream = _Client.GetStream(); Task.Run(() => DataReceiver(), _Token); Console.WriteLine("Connected to tcp://127.0.0.1:9000, ENTER to exit"); Console.ReadLine(); _TokenSource.Cancel(); }
void ConnectThread(object _maxRetryCount) { int maxRetryCount = _maxRetryCount as int? ?? 0; int waitTime = 500; netClient = new TcpClient(); for (int i = 0; i <= maxRetryCount; ++i, waitTime *= 2) { try { netClient = new TcpClient(); var asyncResult = netClient.BeginConnect(hostname, port, null, null); try { // Stop what we're doing if the connection is cancelled from the main thread if (EventWaitHandle.WaitAny(new WaitHandle[] { connectDone, asyncResult.AsyncWaitHandle }) == 0) { netClient.Close(); netClient = null; return; } netClient.EndConnect(asyncResult); } finally { asyncResult.AsyncWaitHandle.Close(); } break; } catch (SocketException ex) { if (i == maxRetryCount) { NotifyConnectionResult(false, ex.Message); return; } else { Thread.Sleep(waitTime); } } } // If the main thread cancels the connection, this will be set to true bool itsOver = false; client.Connect(netClient.GetStream()); client.LogIn(username, password, (sender, e) => { if (itsOver) { return; } NotifyConnectionResult(e.Success, e.ResultMessage); connectDone.Set(); }); connectDone.WaitOne(); itsOver = true; }