public bool PingHost(string IP, int Port) { try { IPEndPoint ip = new IPEndPoint(IPAddress.Parse(IP), Port); TcpClient server = new TcpClient(); IAsyncResult ar = server.BeginConnect(IP, Port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { server.Close(); return(false); } server.EndConnect(ar); return(true); } finally { wh.Close(); } } catch (SocketException) { return(false); } }
private void checkNoBytesTimer_Tick(object sender, EventArgs e) { if (chkNoBytes.Checked == true) { RasConnection r = RasConnection.GetActiveConnectionByName(detectedList.Items[detectedList.SelectedIndex].ToString(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User)); if (r != null) { using (TcpClient tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect("google.com", 80, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { tcp.Close(); appendLog("No Bytes. Disconnecting..."); r.HangUp(); } } finally { wh.Close(); } } } } }
public bool ClientConnect() { try { // 建立 Client tcpClient = new TcpClient(); // 測試連線是否存在 TimeOut 2 Second IAsyncResult result = tcpClient.BeginConnect(serverIP, serverPort, null, null); System.Threading.WaitHandle handler = result.AsyncWaitHandle; if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false)) { tcpClient.Close(); tcpClient.EndConnect(result); handler.Close(); throw new TimeoutException(); } // 連線至 Server tcpClient.Connect(serverIP, serverPort); clientSocket = tcpClient.Client; Debug.Log("連線成功"); return(true); } catch { Debug.Log("連線失敗"); return(false); } }
private bool IsConnected(string ipAddress) { bool connected = false; using (TcpClient client = new TcpClient()) { IAsyncResult ar = client.BeginConnect(ipAddress, 9100, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), false)) { client.Close(); connected = false; throw new TimeoutException(); } client.EndConnect(ar); connected = true; } catch (Exception ex) { return(false); } finally { wh.Close(); } client.Close(); } return(connected); }
private const int TIMEOUT = 1; // seconds public Server() { tcpClient = new TcpClient(); try { IAsyncResult ar = tcpClient.BeginConnect("localhost", 8100, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(TIMEOUT), false)) { tcpClient.Close(); throw new TimeoutException(); } tcpClient.EndConnect(ar); } finally { wh.Close(); } // spin off listener to new thread Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(tcpClient); Send("Hello from XNA!"); SubscribeToGameEvents(); } catch { Console.WriteLine("Could not connect to TCP server!"); } }
public void trySocket(string ip, int port, int timeout) { //Create socket connection try { //TcpClient client = new TcpClient(ip, port); using (TcpClient tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(timeout, false)) { tcp.Close(); throw new TimeoutException(); } tcp.EndConnect(ar); } finally { wh.Close(); } } Console.Out.WriteLine(ip + "\t" + port + "\tS"); } catch (Exception e) { if (!openonly) { Console.Out.WriteLine(ip + "\t" + port + "\tF\t" + e.Message); } } }
public bool ConnectToTCPServerTestMessage(string ip, int port) { //this is test code bool b = false; using (TcpClient tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect("10.10.10.7", 80, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { tcp.Close(); b = false; } else { b = true; tcp.EndConnect(ar); } } finally { wh.Close(); } } return(b); try { System.Console.WriteLine("testing network"); //find a port that works 6000-61000 //"10.10.10.7", 80 tc = new TcpClient(ip, port); ns = tc.GetStream(); sw = new StreamWriter(ns); //sr = new StreamReader(); //send data to pc sw.WriteLine("hello\r\n"); sw.Flush(); //sr.Close(); sw.Close(); ns.Close(); tc.Close(); } catch (Exception ee) { System.Console.WriteLine("Exception testing network:" + ee.Message); return(false); } System.Console.WriteLine("testing network completed"); return(true); }
}//ConnectToServer() // // // // // // **** Try Connect To Client() **** // private bool TryConnectToClient(IPEndPoint ip, out TcpClient client) { client = null; bool isSuccess = false; TcpClient tcpClient = null; System.Threading.WaitHandle waitHandle = null; try { tcpClient = new TcpClient(); IAsyncResult async = tcpClient.BeginConnect(ip.Address, ip.Port, null, null); waitHandle = async.AsyncWaitHandle; if (!async.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(m_ConnectTimeout), false)) { tcpClient.Close(); isSuccess = false; } else { tcpClient.EndConnect(async); client = tcpClient; isSuccess = true; } } catch (Exception ex) { if (tcpClient != null) { tcpClient.Close(); } OnInternalMessage(string.Format("TryConnectToClient exception: {0}.", ex.Message)); isSuccess = false; } finally { if (waitHandle != null) { waitHandle.Close(); } } // Exit. return(isSuccess); } //TryConnectToClient()
/// <summary> /// Connect with timeout /// </summary> /// <param name="connectTimeout">connect timeout. In millisecond</param> public void Connect(int connectTimeout) { if (connectTimeout > 30000) { Connect(); return; } if (_Client == null) { _Client = new System.Net.Sockets.TcpClient(); } IPEndPoint serverEndPoint = new IPEndPoint(RemoteAddress, Port); IAsyncResult ar = _Client.BeginConnect(serverEndPoint.Address, serverEndPoint.Port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(connectTimeout, false)) { _Client.Close(); throw new TimeoutException(string.Format("Try to connect {0} timeout", serverEndPoint)); } _Client.EndConnect(ar); } finally { wh.Close(); } _ClientStream = _Client.GetStream(); if (_Async) { _Thread = new Thread(AsyncMessageRecv); _Thread.IsBackground = true; _Thread.Start(); } }
/// <summary> /// Connects to a given IPEndPoint /// Doesn't allow failed connections /// </summary> /// <param name="ipEndPoint"></param> /// <returns></returns> private static bool ConnectToServerAsync(System.Net.IPEndPoint ipEndPoint) { m_client = new TcpClient(); bool connectionSuceeded = false; //sets up an asyncronos connection IAsyncResult ar = m_client.BeginConnect(ipEndPoint.Address, ipEndPoint.Port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { //blocks the current thread until either timeout is reached or connection is successful if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3), false)) { m_client.Close(); System.Diagnostics.Debug.WriteLine("The server is not running"); return(connectionSuceeded = false); } m_client.EndConnect(ar); } catch (Exception e) { System.Console.WriteLine(e.Message); return(false); } finally { wh.Close(); } connectionSuceeded = true; // create a thread to handle data received from Server Thread HandleDataFromServerThread = new Thread(new ParameterizedThreadStart(HandleDataFromServer)); HandleDataFromServerThread.Name = "Handle Data From Server Thread"; HandleDataFromServerThread.IsBackground = true; HandleDataFromServerThread.Start(m_client); return(connectionSuceeded); }
/// <summary> /// Check server port for open /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <param name="timeout"> </param> /// <returns></returns> public static bool IsPortOpened(string address, int port, int timeout = 3) { var ip = System.Net.Dns.GetHostAddresses(address)[0]; AutoResetEvent connectDone = new AutoResetEvent(false); TcpClient client = new TcpClient(); // connect with timeout // http://stackoverflow.com/questions/795574/c-sharp-how-do-i-stop-a-tcpclient-connect-process-when-im-ready-for-the-progr try { using (TcpClient tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false)) { tcp.Close(); throw new TimeoutException(); } tcp.EndConnect(ar); } finally { wh.Close(); } } } catch (Exception) { return(false); } return(true); }
public void connect2Server() { // tries to connect for 2 seconds and then throws an error if it cannot connect // taken adapted from https://social.msdn.microsoft.com/Forums/vstudio/en-us/2281199d-cd28-4b5c-95dc-5a888a6da30d/tcpclientconnect-timeout client = new TcpClient(); IAsyncResult ar = client.BeginConnect(ipAddress, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false)) { client.Close(); throw new TimeoutException(); } client.EndConnect(ar); } finally { wh.Close(); } print("SOCKET READY"); }
public bool ConnectToHost(System.Net.IPAddress address, int port) { #region TCPClientConnection tcpClient = new TcpClient(); log.Info("Connecting....."); IAsyncResult ar = tcpClient.BeginConnect(address, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { tcpClient.Close(); connected = false; log.Error("TCP Connection to " + address + "port " + port.ToString() + " timeout"); throw new TimeoutException(); } tcpClient.EndConnect(ar); connected = true; log.Error("TCP Connection to " + address + "port " + port.ToString() + " completed"); ipaddresstohost = address; } catch (Exception ex) { return(false); } finally { wh.Close(); } return(true); #endregion }//connect to Telnet server
public static void Dispose(this WaitHandle handle) { handle.Close(); }
private object GetSyncResponse(int id, WaitHandle waitHandle, TimeSpan timeout) { bool signal = waitHandle.WaitOne(timeout, false); waitHandle.Close(); lock(libspotify.Mutex) { try { if (signal && states.ContainsKey(id)) return states[id]; else return null; } finally { states.Remove(id); } } }
private long reconnectInterval = 1 * 10000000; // Ticks between re-connection attempts void initializeConnection() { int connectTimeout = 250; int liveTimeout = 2500; #if !UNITY_IOS Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); #endif if (tcpClient != null) { shutdownConnection(); } // Async start the connection process tcpClient = new TcpClient(); System.IAsyncResult asyncResult = tcpClient.BeginConnect(host, port, null, null); System.Threading.WaitHandle handle = asyncResult.AsyncWaitHandle; try { asyncResult.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(50)); if (!tcpClient.Connected) { tcpClient.Close(); Debug.Log("Failed to connect to Sound-O-Matic server on " + host + ":" + port, this); lastConnectionTimestamp = System.DateTime.UtcNow.Ticks; return; // We failed... too bad } } finally { handle.Close(); } tcpClient.SendTimeout = connectTimeout; tcpClient.ReceiveTimeout = connectTimeout; tcpClient.SendBufferSize = 32 * 1024; Stream stream = tcpClient.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream); writer.AutoFlush = false; writer.NewLine = "\n"; clientInitialized = true; sendPacket("hi UnitySoundOMaticClient " + versionString); flush(); // Check that we got the attention of the server by reading a line here, potentially timing out the connect process already string greeting = reader.ReadLine(); if (!greeting.StartsWith("hi")) { // This is wrong, fail! shutdownConnection(); Debug.Log("Network error: " + greeting, this); return; } else { // We have connection, set up reader thread ThreadStart threadDelegate = new ThreadStart(this.serverStreamParser); Thread newThread = new Thread(threadDelegate); //newThread.Start(); } // We are happy, server is happy, let's get going for real now! tcpClient.SendTimeout = liveTimeout; tcpClient.ReceiveTimeout = liveTimeout; sendPacket("# --------- Connection starting ----------"); #if UNITY_EDITOR sendPacket("# Scene: " + EditorApplication.currentScene); #else sendPacket("# Scene: " + Application.loadedLevelName); #endif //Set soundbase data sendPacket("soundbase " + soundbaseUsername + " " + soundbasePassword + " " + soundbaseUrl); // Prep the state trackers sendPacket("# Preparing state handlers..."); AudioNode[] nodes = GetComponentsInChildren <AudioNode>() as AudioNode[]; Dictionary <string, int> filterCounter = new Dictionary <string, int>(); Dictionary <int, int> audioCounter = new Dictionary <int, int>(); int nodeCounter = 0; int filterTotalCounter = 0; foreach (AudioNode child in nodes) { child.resetStateTrackers(); if (child.getNodeTypeString() == "soundbase") { if (audioCounter.ContainsKey(child.audioIdentifier)) { audioCounter[child.audioIdentifier]++; } else { audioCounter[child.audioIdentifier] = 1; } } VSTFilter[] childFilters = child.gameObject.GetComponents <VSTFilter>(); foreach (VSTFilter filter in childFilters) { if (filterCounter.ContainsKey(filter.getFilterName())) { filterCounter[filter.getFilterName()]++; } else { filterCounter[filter.getFilterName()] = 1; } filterTotalCounter++; } nodeCounter++; } // Send preloading info string preloadAudioString = ""; bool firstComma = true; foreach (KeyValuePair <int, int> entry in audioCounter) { if (firstComma) { firstComma = false; } else { preloadAudioString += ", "; } preloadAudioString += entry.Key + ":" + entry.Value; } sendPacket("preloadAudio {" + preloadAudioString + "}"); string preloadFiltersString = ""; firstComma = true; foreach (KeyValuePair <string, int> entry in filterCounter) { if (firstComma) { firstComma = false; } else { preloadFiltersString += ", "; } preloadFiltersString += entry.Key + ":" + entry.Value; } sendPacket("preloadFilters {" + preloadFiltersString + "}"); sendPacket("# " + nodeCounter + " AudioNodes prepared"); sendPacket("# " + filterTotalCounter + " VSTFilters prepared"); ListenerNode[] lNodes = Resources.FindObjectsOfTypeAll(typeof(ListenerNode)) as ListenerNode[]; nodeCounter = 0; this.resetStateTrackers(); foreach (ListenerNode child in lNodes) { child.resetStateTrackers(); nodeCounter++; } sendPacket("# " + nodeCounter + " ListenerNodes prepared"); sendPacket("# --------- Connection started -----------"); Debug.Log("Connected to Sound-O-Matic server on " + host + ":" + port, this); }
public static string TestConnection(string serverIP, int port) { try { using (TcpClient tcp = new TcpClient()) { IAsyncResult ar = tcp.BeginConnect(serverIP, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(0.5), false)) { tcp.Close(); } tcp.EndConnect(ar); output = "Received Connection"; } catch { output = "No Connection"; } finally { wh.Close(); } } // string message = "TestConnection"; // // Create a TcpClient. // // The client requires a TcpServer that is connected // // to the same address specified by the server and port // // combination. // TcpClient client = new TcpClient(); // client // client.SendTimeout = 100; // client.ReceiveTimeout = 100; // client.Connect(serverIP, Convert.ToInt32(port)); // // Translate the passed message into ASCII and store it as a byte array. // Byte[] data = new Byte[4096]; // data = System.Text.Encoding.ASCII.GetBytes(message); // // Get a client stream for reading and writing. // // Stream stream = client.GetStream(); // NetworkStream stream = client.GetStream(); // // Send the message to the connected TcpServer. // stream.Write(data, 0, data.Length); // output = "Sent: " + message; // // Essential.BaseAlert.ShowAlert("Socket Message", output, BaseAlert.Buttons.Ok, BaseAlert.Icons.Information); // // Buffer to store the response bytes. // data = new Byte[4096]; // // String to store the response ASCII representation. // String responseData = String.Empty; // // Read the first batch of the TcpServer response bytes. // Int32 bytes = stream.Read(data, 0, data.Length); // responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); // output = "Received: " + responseData; // // Essential.BaseAlert.ShowAlert("Socket Message", output, BaseAlert.Buttons.Ok, BaseAlert.Icons.Information); // // Close everything. // stream.Close(); // client.Close(); } catch (ArgumentNullException e) { output = "ArgumentNullException: " + e; //Essential.BaseAlert.ShowAlert("Socket Message", output, BaseAlert.Buttons.Ok, BaseAlert.Icons.Information); } catch (SocketException e) { output = "SocketException: " + e.ToString(); //Essential.BaseAlert.ShowAlert("Socket Message", output, BaseAlert.Buttons.Ok, BaseAlert.Icons.Information); } return(output); }
public void dataStream(object client_obj) { //Gecko Connection try { client = new TcpClient(); client.NoDelay = true; IAsyncResult ar = client.BeginConnect((string)client_obj, 7335, null, null); //Auto Splitter Input Display uses 7335 System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3), false)) { client.Close(); MessageBox.Show("WiiU: Connection Timeout!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); if (ControllerDisconnected != null) { _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null); } return; } client.EndConnect(ar); } finally { wh.Close(); } } catch (Exception) { MessageBox.Show("WiiU: Connection Error. Check IP Address!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); if (ControllerDisconnected != null) { _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null); } return; } //Handle Connection stream = client.GetStream(); EndianBinaryReader reader = new EndianBinaryReader(stream); try { float StickX, StickCX, StickY, StickCY = 0.0f; byte Buttons1, Buttons2, Buttons3 = 0; while (true) { byte cmd_byte = reader.ReadByte(); switch (cmd_byte) { case 0x01: //Input Data { //1 = 0 bit, 2 = 1 bit, 4 = 2 bit, 8 = 3 bit, 16 = 4 bit, 32 = 5 bit, 64 = 6 bit, 128 = 7 bit //Apply Inputs var outState = new ControllerStateBuilder(); StickX = reader.ReadSingle(); StickY = reader.ReadSingle(); if (StickX <= 1.0f && StickY <= 1.0f && StickX >= -1.0f && StickY >= -1.0f) { outState.SetAnalog("lstick_x", StickX); outState.SetAnalog("lstick_y", StickY); } StickCX = reader.ReadSingle(); StickCY = reader.ReadSingle(); if (StickCX <= 1.0f && StickCY <= 1.0f && StickCX >= -1.0f && StickCY >= -1.0f) { outState.SetAnalog("cstick_x", StickCX); outState.SetAnalog("cstick_y", StickCY); } Buttons1 = reader.ReadByte(); Buttons2 = reader.ReadByte(); Buttons3 = reader.ReadByte(); outState.SetButton("a", IsBitSet(Buttons1, 7)); outState.SetButton("b", IsBitSet(Buttons1, 6)); outState.SetButton("x", IsBitSet(Buttons1, 5)); outState.SetButton("y", IsBitSet(Buttons1, 4)); outState.SetButton("left", IsBitSet(Buttons1, 3)); outState.SetButton("right", IsBitSet(Buttons1, 2)); outState.SetButton("up", IsBitSet(Buttons1, 1)); outState.SetButton("down", IsBitSet(Buttons1, 0)); outState.SetButton("zl", IsBitSet(Buttons2, 7)); outState.SetButton("zr", IsBitSet(Buttons2, 6)); outState.SetButton("l", IsBitSet(Buttons2, 5)); outState.SetButton("r", IsBitSet(Buttons2, 4)); outState.SetButton("plus", IsBitSet(Buttons2, 3)); outState.SetButton("minus", IsBitSet(Buttons2, 2)); outState.SetButton("l3", IsBitSet(Buttons2, 1)); outState.SetButton("r3", IsBitSet(Buttons2, 0)); outState.SetButton("home", IsBitSet(Buttons3, 1)); outState.SetButton("touch", IsBitSet(Buttons3, 2)); if (ControllerStateChanged != null) { _context.Post((SendOrPostCallback)(_ => ControllerStateChanged(this, outState.Build())), null); } break; } default: throw new Exception("Invalid data"); } } } catch (ThreadAbortException) { } catch (Exception) { if (ControllerDisconnected != null) { _context.Post((SendOrPostCallback)(_ => ControllerDisconnected(this, EventArgs.Empty)), null); } } }
private void BkgWorker_DoWork(object sender, DoWorkEventArgs e) { TcpClient client = new TcpClient(); byte[] name = Encoding.UTF8.GetBytes(System.IO.Path.GetFileName(filePath)); byte[] size = BitConverter.GetBytes(name.Length); byte[] buffer = new byte[1024]; Array.Copy(size, 0, buffer, 0, size.Length); Array.Copy(name, 0, buffer, 4, name.Length); IAsyncResult ar = client.BeginConnect(ip, MainWindow.portTcp, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) { client.Close(); foreach (ToSend p in listSend) { if (p.ip.Equals(ip)) { listSend.Remove(p); break; } } throw new TimeoutException(); } client.EndConnect(ar); } finally { wh.Close(); } client.Client.Send(buffer, 0, name.Length + size.Length, SocketFlags.None); client.Client.Receive(buffer, 1024, SocketFlags.None); string response = Encoding.ASCII.GetString(buffer); if (!response.Substring(0, 2).Equals("OK")) { return; } FileStream fs = File.OpenRead(filePath); byte[] file = new byte[4096]; size = BitConverter.GetBytes(fs.Length); client.Client.Send(size, 0, size.Length, SocketFlags.None); client.Client.Receive(buffer, 1024, SocketFlags.None); response = Encoding.ASCII.GetString(buffer); if (!response.Substring(0, 2).Equals("OK")) { client.Close(); fs.Close(); MessageBox.Show(this.name + " doesn't accept the file"); return; } float count = 0; int nRead = 0; percentage = 0; rimanente = "30 seconds"; bkgWorker.ReportProgress((int)percentage); double time1; int tenPeriod = 0; DateTime started = DateTime.Now; while (count < fs.Length) { nRead = fs.Read(file, 0, 4096); count += client.Client.Send(file, 0, nRead, SocketFlags.None); percentage = (float)((count / (float)fs.Length) * 100); if (tenPeriod++ > 10) { TimeSpan elapsedTime = DateTime.Now - started; TimeSpan estimatedTime = TimeSpan.FromSeconds( (fs.Length - count) / ((double)count / elapsedTime.TotalSeconds)); int hours = (int)estimatedTime.Hours; int minute = (int)estimatedTime.Minutes; int seconds = (int)estimatedTime.Seconds; if (hours > 0) { rimanente = hours.ToString() + " hour " + minute.ToString() + " min"; } else if (minute > 0) { rimanente = minute.ToString() + " minutes " + seconds.ToString() + " sec"; } else { rimanente = seconds.ToString() + " seconds"; } } if (bkgWorker.CancellationPending) { fs.Close(); client.Client.Send(file, 0, 1, SocketFlags.None); client.Close(); return; } bkgWorker.ReportProgress((int)percentage); // Dispatcher.BeginInvoke(new Action(() => { pb.Value += (count / file.Length) * 100; })); } fs.Close(); client.Client.Receive(buffer, 1024, SocketFlags.None); response = Encoding.ASCII.GetString(buffer); if (!response.Substring(0, 2).Equals("OK")) { return; } client.Close(); // Dispatcher.BeginInvoke(new Action(() => { Thread.Sleep(3000);pib.progressBarGrid.Visibility = Visibility.Collapsed; })); }