private void btnConnectEP(object sender, RoutedEventArgs e) { string btnContent = (string)((Button)sender).Content; if (btnContent == "Connected!" || btnContent == "Connecting...") { return; } IPEndPoint serverEP; IPAddress serverIP; try { string strIPAdress = txbEndPoint.Text.Split(':')[0]; int port = int.Parse(txbEndPoint.Text.Split(':')[1]); serverIP = IPAddress.Parse(strIPAdress); serverEP = new IPEndPoint(serverIP, port); } catch { ShowOverlayMessage("Can't connect to server, Please check your information!"); return; } workingResources.CurrentSocket = new Socket(serverIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketOpreation socketOpration = new SocketOpreation(1024); socketOpration.Socket = workingResources.CurrentSocket; socketOpration.State = sender; workingResources.CurrentSocket.BeginConnect(serverEP, ConnectCallBack, socketOpration); ((Button)sender).Content = "Connecting..."; }
private void ConnectCallBack(IAsyncResult ar) { SocketOpreation socketOpreation = (SocketOpreation)ar.AsyncState; Socket socket = socketOpreation.Socket; Button btn = (Button)socketOpreation.State; Dispatcher.Invoke(() => { btn.Content = "Connected!"; }); try { socket.EndConnect(ar); } catch { return; } }