static void Main(string[] args) { Socket s=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPoint ie=new IPEndPoint(IPAddress.Parse("127.0.0.1"),9000); s.Connect(ie); Console.WriteLine("Connected to Server....."); byte[] data=new byte[1024]; int k=s.Receive(data); Console.WriteLine("Loi chao tu Server:{0}",Encoding.ASCII.GetString(data,0,k)); while(true) { Console.WriteLine("Moi nhap du lieu can tinh"); string st=Console.ReadLine(); byte[] dl=new byte[1024]; dl=Encoding.ASCII.GetBytes(st); s.Send(dl,dl.Length,SocketFlags.None); if(st.ToUpper().Equals("QUIT")) break; dl=new byte[1024]; int k1=s.Receive(dl); Console.WriteLine("Ket qua tinh tong tu server tra ve:{0}", Encoding.ASCII.GetString(dl, 0, k1)); } s.Disconnect(true); s.Close(); }
private void btnkq_Click(object sender, EventArgs e) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ie = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000); s.Connect(ie); byte[] data = new byte[1024]; int k = s.Receive(data); MessageBox.Show("welcome",Encoding.ASCII.GetString(data,0,k)); while (true) { String strA = txta.Text.ToString(); String strB = txtb.Text.ToString(); String str = strA + strB; byte[] dl = new byte[1024]; dl = Encoding.ASCII.GetBytes(str); s.Send(dl, dl.Length, SocketFlags.None); if (str.ToUpper().Equals("QUIT")) break; dl = new byte[1024]; int k1 = s.Receive(dl); String KQ = Encoding.ASCII.GetString(dl,0,k1); txtkq.Text = KQ.ToString(); } s.Disconnect(true); s.Close(); }
public void TestMethod1() { Uri uri = new Uri("http://bionic-university.com/"); string message = string.Format( "GET {0} HTTP/1.1\r\nHost: {1}\r\nConnection: close\r\nAccept: text/html\r\ntUser-Agent: MyBrowser\r\n\r\n", uri.PathAndQuery, uri.Host); string output = string.Empty; IPHostEntry IpHost = Dns.GetHostEntry(uri.Host); IPAddress[] ips = IpHost.AddressList; IPEndPoint ipe = new IPEndPoint(ips[0], uri.Port); using (Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(ipe); byte[] bytesSent = Encoding.ASCII.GetBytes(message); byte[] received = new byte[1024]; socket.Send(bytesSent); int bytes = 0; do { bytes = socket.Receive(received, received.Length, 0); output += Encoding.ASCII.GetString(received); } while (bytes > 0); socket.Disconnect(false); } }
public Exception Connect() { try { _socket.Connect(Host, Port); } catch (Exception e) { return(e); } NetStream = new NetworkStream(_socket); if (HandShake()) { try { DataReceiveThread = new Thread(DataReceiveLoop) { IsBackground = true }; DataReceiveThread.Start(); Ping(); } catch (Exception e) { Info = e.Message; PingTimeStamp = 0; _socket.Disconnect(true); } } return(null); }
public static IEnumerable<int> Scan(string ip, int startPort, int endPort) { List<int> openPorts = new List<int>(); for (int port = startPort; port <= endPort; port++) { Debug.WriteLine(string.Format("Scanning port {0}", port)); Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); try { scanSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); scanSocket.Disconnect(false); openPorts.Add(port); //scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port }); } catch(Exception ex) { //bury exception since it means we could not connect to the port } } return openPorts; }
private void button1_Click(object sender, EventArgs ev) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect("192.168.16.170", 10000); byte[] buf; buf = new byte[] { 0x00,0x06,0x10,0x12,0x00,0x00 }; s.Send(buf); byte[] rec=new byte[128]; int r = 0; s.ReceiveTimeout = 1000; try { r = s.Receive(rec); Debug.WriteLine(FUNC.BytesToString(rec, 0, r)); r = s.Receive(rec); Debug.WriteLine(FUNC.BytesToString(rec, 0, r)); } catch (Exception e) { Debug.WriteLine(e.Message); } s.Disconnect(false); }
private void ListenerThread() { while (!_stopThreads) { Socket client = null; try { client = _listenSocket.Accept(); } catch (Exception) { break; } if (client == null) { continue; } if (!OnClientConnected((client.RemoteEndPoint as IPEndPoint).Address)) { #if (MF) client.Close(); #else client.Disconnect(false); client.Close(); #endif continue; } CreateWorkerProcess(client); } }
private static bool CheckEndpoint(IPEndPoint solrEndpoint) { var valid = false; using (var s = new Socket(solrEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { try { s.Connect(solrEndpoint); if (s.Connected) { valid = true; s.Disconnect(true); } else { valid = false; } } catch { valid = false; } } return valid; }
/// <summary> /// /// </summary> /// <returns></returns> public FunctionResult TcpDisconnectClientToServer() { try { TcpConnectClientSocket.Disconnect(false); // un-reuseable socket } catch (PlatformNotSupportedException) { // log information FFTAICommunicationManager.Instance.Logger.WriteLine("PlatformNotSupportedException", true); return(FunctionResult.PlatformNotSupportedException); } catch (ObjectDisposedException) { // log information FFTAICommunicationManager.Instance.Logger.WriteLine("ObjectDisposedException", true); return(FunctionResult.ObjectDisposedException); } catch (SocketException) { // log information FFTAICommunicationManager.Instance.Logger.WriteLine("SocketException", true); return(FunctionResult.SocketException); } return(FunctionResult.Success); }
private void TryCloseSocket() { if (_inner_socket != null) { try { _inner_socket.Shutdown(SocketShutdown.Both); } catch (Exception e) { } try { _inner_socket.Disconnect(false); } catch (Exception e) { } try { _inner_socket.Close(); } catch (Exception e) { } /* #if !UNITY_EDITOR * try * { * _inner_socket.Dispose(); * } * catch (Exception e) { } #endif */ _inner_socket = null; } }
public void Dispose() { try { AddClient = null; RemoveClient = null; DataChange = null; DataRecive = null; DataSent = null; if (ListenerSocker != null) { ListenerSocker.Shutdown(SocketShutdown.Both); if (ListenerSocker.Connected) { ListenerSocker.Disconnect(true); } ListenerSocker.Close(); ListenerSocker.Dispose(); } for (int i = 0; i < Connections.Count; i++) { Connections[i].Close(); Connections[i].Dispose(); } } catch { } ListenerSocker = null; Connections = null; Log.Log.GetLog().Info(this, "Dispose"); GC.SuppressFinalize(this); }
public static void FullClose(this System.Net.Sockets.Socket s) { try { s.Shutdown(SocketShutdown.Both); } catch (Exception) { } try { s.Disconnect(false); } catch (Exception) { } try { s.Close(); } catch (Exception) { } try { s.Dispose(); } catch (Exception) { } }
/// <summary> /// 发送消息完成的回调函数 /// </summary> /// <param name="ar"></param> private void OnSendMessageComplete(IAsyncResult ar) { var data = ar.AsyncState as byte[]; SocketError socketError; _socket.EndSend(ar, out socketError); if (socketError != SocketError.Success) { _socket.Disconnect(false); throw new SocketException((int)socketError); } if (SendMessageCompleted != null) { SendMessageCompleted(this, new SocketEventArgs(data)); } //Debug.Log("Send message successful !"); }
/** * Closes the socket connection. */ public void Disconnect() { if (Connected) { penguinSocks.Shutdown(Sockets.SocketShutdown.Both); penguinSocks.Disconnect(true); } }
public void Disconnect(Socket s) { if (s.Connected) { s.Shutdown(SocketShutdown.Both); s.Disconnect(true); s.Close(); } }
public static void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. // The DNS name of the computer // running the listener is "host.contoso.com". IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11337); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket = listener; // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(100); running = true; while (running == true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. ServerLog(null, new Logging.LogEventArgs("Waiting for a connection...")); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } listener.Disconnect(true); } catch (Exception e) { ServerLog(null, new Logging.LogEventArgs(e.ToString())); } ServerLog(null, new Logging.LogEventArgs("\nPress ENTER to continue...")); Console.Read(); }
private async void ProcessConnection(Socket Client) { NetworkStream ClientStream = new NetworkStream(Client); if (await this.Handshaker.HandshakeConnection(ClientStream)) { this.FinalizeConnection(Client, ClientStream); } else { //find propper way to disconnect Client.Disconnect(false); } }
private void Connect_Click(object sender, EventArgs e) { if (ConnectToRobot.Checked) { Socket m_CommandSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPAddress AddressToUse = null; if (!IPAddress.TryParse(HostName.Text,out AddressToUse)) { foreach (IPAddress Address in Dns.GetHostEntry(HostName.Text).AddressList) if (Address.AddressFamily == AddressFamily.InterNetwork) AddressToUse = Address; } m_CommandSocket.ReceiveTimeout = 1000; m_CommandSocket.SendTimeout = 1000; m_CommandSocket.Connect(new IPEndPoint(AddressToUse, 3000)); byte[] buf = new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }; m_CommandSocket.Send(buf); m_CommandSocket.Receive(buf); m_CommandSocket.Disconnect(false); } catch { MessageBox.Show("Cannot connect to specified host"); DialogResult = DialogResult.Retry; return; } RegistryKey SettingsKey = Registry.CurrentUser.CreateSubKey("Software\\Nasa\\NasaBot"); SettingsKey.SetValue("Host", HostName.Text); }//ConnectToRobot end // else if (NavigationPlanning.Checked) // { // m_ControlWindow = new Control(m_Robot); // m_ControlWindow.Show(); // } Close(); }
protected void CloseSocket(Socket socket) { try { socket.Close(); socket.Disconnect(false); } catch (ObjectDisposedException) { } catch (SocketException) { } }
public void Disconnect(Socket s) { try { if (s != null && s.Connected) { s.Disconnect(true); } //s.Shutdown(SocketShutdown.Both); } catch (Exception ex) { Log.Exception("[Client.Disconnect] ", ex); } }
/// <summary> /// Stop listening and close the current socket connection, also releases all resources. /// </summary> private void StopListeningEx() { _isListening = false; try { // Stop polling. _multiplexer.StopPolling(); } catch { } try { // Clear last error. ClearLastError(); // Shutdown the socket. if (_socket != null) { _socket.Shutdown(SocketShutdown.Both); } } catch (Exception ex) { SetLastError(ex); } try { // Close the socket. if (_socket != null) { _socket.Disconnect(false); } } catch { } try { // Close the socket. if (_socket != null) { _socket.Close(); _socket.Dispose(); } } catch { } }
public void SendCommand(string command) { try { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(_EndPoint); socket.Send(Encoding.UTF8.GetBytes(command)); socket.Disconnect(true); socket.Close(); } catch (Exception ex) { Console.WriteLine(ex); throw; } }
public Exception Disconnect() { NetStream?.Dispose(); NetStream = null; try { _socket?.Disconnect(true); } catch (Exception e) { return(e); } return(null); }
internal static void SafeCloseSocket(System.Net.Sockets.Socket socket) { try { socket.Disconnect(false); } catch { } try { socket.Close(); } catch { } }
public static void Stop() { try { _client2?.Disconnect(false); _client2?.Dispose(); _stopReceiving = true; _reconnected = true; _timer?.Stop(); _timer?.Dispose(); } catch (Exception ex) { LogUtils.Error($"{ex}"); } }
public byte[] GetResponse() { IPAddress serverIp = IPAddress.Parse(NetOperator.serverIP); IPEndPoint iep = new IPEndPoint(serverIp, NetOperator.serverPort); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(iep); //byte[] byteMessage; //byteMessage = Encoding.ASCII.GetBytes(content); socket.Send(content); byte[] temp = new byte[1024]; int read = socket.Receive(temp, 0, 1024, SocketFlags.None); byte[] result=new byte[read]; Array.Copy(temp, 0, result, 0, read); socket.Shutdown(SocketShutdown.Both); socket.Disconnect(false); socket.Close(); return temp; }
/// <summary> /// 测试socket连接 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="err"></param> /// <returns></returns> public static bool SocketConnectTo(string ip, string port, out string err) { err = ""; try { Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint p = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)); sck.Connect(p); sck.Disconnect(false); sck.Close(); return true; } catch (Exception ex) { err = string.Format("连接{0}:{1}失败,失败原因:", ip, port) + ex.Message; return false; } }
static void Main(string[] args) { int total_count = 100000; int cur_count = 0; while(cur_count < total_count) { cur_count++; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 90)); Thread.Sleep(1000); sock.Disconnect(true); sock.Close(); sock = null; } }
public static Socket Send(string ipAddress, int port, byte[] data) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port); // IPEndPoint ep = new IPEndPoint((Dns.Resolve(IPAddress.Any.ToString())).AddressList[0], port); s.Connect(ep); s.Send(BitConverter.GetBytes(Convert.ToInt32(CommandType.SendHashData))); string hashtable = "HashtableName"; string key = "HashtableName"; object value = new object(); s.Send(data); s.Disconnect(true); return s; }
public void ProcessClient(Socket client) { //System.Threading.Thread.Sleep(50); //Small delay so the process will be using 0-1% cpu usage at flood attack if (File_MaxConnections.AcceptConnection(client.RemoteEndPoint)) { int ID = _clientList.Count; FileClients c = new FileClients(client, NetworkKey); _clientList.Add(ID, c); c.DisconnectHandle = OnDisconnect; c.ClientID = ID; settings.ClientsConnected++; Logger.AddLog(new LogInfo("Incoming client", "Accepted")); } else { client.Disconnect(false); client = null; } }
public static bool LocalPortIsAvailable(int port) { var localhost = Dns.GetHostAddresses("localhost")[0]; try { var sock = new Socket(localhost.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sock.Connect(localhost, port); if (sock.Connected) // RemotingPort is in use and connection is successful { sock.Disconnect(false); sock.Dispose(); return false; } throw new Exception("Not connected to port ... but no Exception was thrown?"); } catch (SocketException ex) { if (ex.ErrorCode == 10061) // RemotingPort is unused and could not establish connection return true; throw ex; } }
public void WaitForData(System.Net.Sockets.Socket soc) { try { if (!soc.Connected == true) { soc.Disconnect(true); } SocketPacket socketPacket = new SocketPacket(); socketPacket.RealmserverSocket = soc; soc.BeginReceive(socketPacket.dataBuffer, 0, socketPacket.dataBuffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), socketPacket); } catch (SocketException se) { ColoredConsole.ConsoleWriteErrorWithOut(se.Message); } }
/// <summary> /// Release the currently used socket. /// </summary> public void ReleaseSocket(bool disposeSocket) { #if Matrix_Diagnostics InstanceMonitor monitor = Monitor; if (monitor != null && monitor.IsReportAllowed) { monitor.Info(string.Format("Releasing socket, dipose [{0}].", disposeSocket)); } #endif lock (_syncRoot) { System.Net.Sockets.Socket socket = _socket; if (socket != null && disposeSocket) { socket.Disconnect(false); socket.Close(); } _socket = null; } }
public void Run() { Running = true; Console.WriteLine("Listener: Starting on port " + Port); Thread.Sleep(500); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); sock.Bind(new IPEndPoint(Dns.Resolve(Host).AddressList[0], Port)); sock.Listen(0); while (Running && Thread.CurrentThread.ThreadState == ThreadState.Running) { Socket conn = null; try { conn = sock.Accept(); } catch (Exception) { } if (conn != null) { Console.WriteLine("Got incoming connection!"); RequestThread requestthread = new RequestThread(); requestthread.Connection = conn; Thread requestthreadthread = new Thread(new ThreadStart(requestthread.Run)); requestthreadthread.Start(); } } Console.WriteLine("Listener: Stopping thread."); sock.Disconnect(false); sock.Close(); Console.WriteLine("Listener: Stopped."); Thread.CurrentThread.Abort(); }
/// <summary> /// Receives bytes from a remote party and puts them in a memory stream. (as opposed to a file) /// </summary> /// <param name="bacon">Socket to receive from</param> /// <param name="cHeader">CedLib contentheader (needed for bytescount)</param> /// <param name="printstatus"></param> /// <returns>Memorystream filled with bytes from remote party.</returns> public static MemoryStream receivebytes(Socket bacon, bool printstatus) { MemoryStream memstream = new MemoryStream(); int chunksize = 1024 * 1024; byte[] receivebytes = new byte[chunksize]; //If done initializing stuff for the receive, send 'OK!' to signal the start of the transfer if (printstatus) Console.WriteLine("Sending response to header"); sendstring(bacon, "OK!\n Continue to send me the bytes"); if (!waitfordata(bacon, 30000, printstatus)) throw new Exception("Time out while waiting for sender to begin transfer."); System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch(); swatch.Start(); if (printstatus) Console.Write("Receiving file.."); long receivedcount = 0; int lastreceive = 1; while (lastreceive > 0 && bacon.Connected) { if (bacon.Connected) lastreceive = bacon.Receive(receivebytes, chunksize, SocketFlags.None); else { if (printstatus) Console.Write("Remote party disconnected. "); break; } memstream.Write(receivebytes, 0, lastreceive); Console.Write("."); receivedcount += lastreceive; } swatch.Stop(); bacon.Shutdown(SocketShutdown.Both); bacon.Disconnect(true); float speedinKB = ((receivedcount / 1024.0f) / (swatch.ElapsedMilliseconds / 1000.0f)); if (printstatus) Console.WriteLine(string.Format("Done! received {0} bytes in {1} milliseconds! ({2}KB/s)", new object[] { receivedcount, swatch.ElapsedMilliseconds, speedinKB })); return memstream; }
public void ConnectToServer(string ip) { Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Blocking = true; // sets the socket into blocking mode. // Change the loopback address to the address of the server. IPEndPoint server = new IPEndPoint(IPAddress.Parse(ip), 8080); try { // Connect to the server. clientSocket.Connect(server); // Disconnect the Socket. clientSocket.Disconnect(true); // Close the Socket. clientSocket.Close(); // Display Connected Message. MessageBox.Show("You connected to the Server... Now we just need to get streaming enabled!", "Information"); } catch (SocketException se) { MessageBox.Show(se.ToString()); } }
/// <summary> /// Close the connection and release all resources. /// </summary> private void CloseEx() { try { if (_socket != null) { _socket.Shutdown(SocketShutdown.Both); } } catch { } try { if (_socket != null) { _socket.Disconnect(false); } } catch { } try { if (_socket != null) { _socket.Close(); } if (_sslStream != null) { _sslStream.Close(); } if (_networkStream != null) { _networkStream.Close(); } } catch { } }
public string GetResponse(Request request) { string connectionMessage = request.ToString(); byte[] sentBytes = Encoding.ASCII.GetBytes(connectionMessage); byte[] receivedBytes = new byte[1024]; string output = string.Empty; int receivedBytesCount = 0; try { IPHostEntry ipHostEntry = Dns.GetHostEntry(request.Uri.Host); //Looking for URI IP-address IPAddress[] ipAddresses = ipHostEntry.AddressList; IPEndPoint ipEndPoint = new IPEndPoint(ipAddresses[0], request.Uri.Port); //Creating an endpiont to get messages from server _socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(ipEndPoint); _socket.Send(sentBytes); do { receivedBytesCount = _socket.Receive(receivedBytes, receivedBytes.Length, 0); //Receiving data until it's done output += Encoding.UTF8.GetString(receivedBytes); } while (receivedBytesCount > 0); } catch (SocketException exc) { output = exc.Message; _socket.Dispose(); throw new Exception(exc.Message); } finally { _socket.Disconnect(false); _socket.Close(); } return output; }
public static void FullClose(this System.Net.Sockets.Socket s) { try { s.Shutdown(SocketShutdown.Both); } catch { // ignored } try { s.Disconnect(false); } catch { // ignored } try { s.Close(); } catch { // ignored } try { s.Dispose(); } catch { // ignored } }
public static bool ValidEmailDomain(string aEmail) { bool ReturnVal = false; string[] Host = aEmail.Split('@'); string HostName = Host[1]; try { IPHostEntry IPHost = Dns.GetHostEntry(HostName); IPEndPoint EndPoint = new IPEndPoint(IPHost.AddressList[0], 25); Socket s = new Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { s.Connect(EndPoint); s.Disconnect(false); ReturnVal = true; } catch (Exception) { ReturnVal = false; } finally { if (s.Connected) s.Disconnect(false); } } catch (Exception) { ReturnVal = false; } return ReturnVal; }
public void Connect() { lock (ClientSocket) { if (ClientSocket == null || !ClientSocket.Connected) { IPHostEntry hostEntry = Dns.GetHostEntry(Hostname); foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, PortNumber); ClientSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, _keepAlive); // 15 second timeout for sending ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, _sendTimeout); // 15 second timeout for receiving ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _receiveTimeout); ClientSocket.Connect(ipe); if (ClientSocket.Connected) { break; } else { continue; } } if (!ClientSocket.Connected) { throw new ApplicationException("Failed to connect to server."); } else { bool authenticated = Authenticate(); if (!authenticated) { ClientSocket.Disconnect(false); } } } } }
void Utils.Wrappers.Interfaces.ISocket.Disconnect(bool reuseSocket) { InternalSocket.Disconnect(reuseSocket); }
/// <summary> /// /// </summary> /// <returns></returns> public FunctionResult UdpDisconnectLocalToRemote() { UdpConnectRemoteSocket.Disconnect(true); return(FunctionResult.Success); }
//Метод, который отрабатывается всякий раз, когда интервал таймера истечёт. private void TimerStart(object sender, ElapsedEventArgs e) { if(!_isDisposed) _sendingTimer.Stop(); if (_unsentPackets.Count == 0) return; var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("Попытка отправить {0} неотправленных пакетов.", _unsentPackets.Count); lock (_listBlocker) { try { socket.Connect(ServerEndPoint); foreach (var unsentPacket in _unsentPackets) { socket.Send(unsentPacket); var responceBuffer = new byte[1024]; var received = socket.Receive(responceBuffer); var responce = Encoding.UTF8.GetString(responceBuffer, 0, received); if (!responce.EndsWith("OK")) throw new Exception("Сервер не подтвердил получение."); } socket.Disconnect(true); if (socket.Connected) socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); Console.WriteLine("{0} отправлены успешно.", _unsentPackets.Count); } catch (Exception ex) { if (socket.Connected) socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); Console.WriteLine(ex.Message); if(!_isDisposed) _sendingTimer.Start(); } } }
public void BeginConnectToIPV4EndPointUsingDualModelSocket () { using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) { var host = new IPEndPoint (IPAddress.Loopback, 0); server.Bind (host); server.Listen (0); var ep = server.LocalEndPoint as IPEndPoint; BCCalledBack.Reset (); var ar1 = client.BeginConnect (ep, BCCallback, client); Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1"); client.Disconnect (true); BCCalledBack.Reset (); var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client); Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2"); client.Disconnect (true); BCCalledBack.Reset (); var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client); Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2"); client.Disconnect (true); } }
public void ConnectToIPV4EndPointUsingDualModelSocket () { using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) { var host = new IPEndPoint (IPAddress.Loopback, 0); server.Bind (host); server.Listen (0); var ep = server.LocalEndPoint as IPEndPoint; client.Connect (ep); client.Disconnect (true); client.Connect (IPAddress.Loopback, ep.Port); client.Disconnect (true); client.Connect (new [] {IPAddress.Loopback}, ep.Port); client.Disconnect (true); } }
public void DisconnectFromServer() { cClientSocket.Disconnect(false); }
public void Disconnect(bool reuseSocket) { socket.Disconnect(reuseSocket); }
public void Dispose() { _socket.Disconnect(true); _socket.Dispose(); }
public async Task DisconnectingClient() { using (var server = new TestServer(App)) { var socket = new Socket(SocketType.Stream, ProtocolType.IP); socket.Connect(IPAddress.Loopback, 54321); await Task.Delay(200); socket.Disconnect(false); socket.Dispose(); await Task.Delay(200); using (var connection = new TestConnection()) { await connection.SendEnd( "GET / HTTP/1.0", "\r\n"); await connection.ReceiveEnd( "HTTP/1.0 200 OK", "\r\n"); } } }
[Category ("NotDotNet")] // "Needs XP or later" public void Disconnect () { Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket listen = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Loopback; IPEndPoint ep = new IPEndPoint (ip, 1255); listen.Bind (ep); listen.Listen (1); sock.Connect (ip, 1255); Assert.AreEqual (true, sock.Connected, "Disconnect #1"); sock.Shutdown (SocketShutdown.Both); sock.Disconnect (false); Assert.AreEqual (false, sock.Connected, "BeginDisconnect #3"); sock.Close (); listen.Close (); }
private void AcceptCallback(IAsyncResult value) { try { if (ListenerSocker == null) { return; } System.Net.Sockets.Socket socket = ListenerSocker.EndAccept(value); if (UseBlockList) { string ip = IP(socket); if (BlockClient.ContainsKey(ip)) { if (BlockClient[ip].IsBlock) { if (BlockClient[ip].Timer > DateTime.Now.Ticks) { Log.Log.GetLog().Info(this, "AcceptCallback Disconnect ip : " + ip); socket.Disconnect(true); } else { BlockClient[ip] = new ClienteSocketBlock(); } } } } if (socket.Connected) { getClientType(socket); } } catch (Exception e) { Log.Log.GetLog().Error(this, "AcceptCallback", e); } finally { try { if (ListenerSocker != null) { ListenerSocker.BeginAccept(new AsyncCallback(AcceptCallback), null); } } catch (Exception e) { Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept", e); try { close(); } catch (Exception ex) { Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept - close", ex); } Thread.Sleep(2000); try { startService(); } catch (Exception ex) { Log.Log.GetLog().Error(this, "AcceptCallback - ListenerSocker.BeginAccept - startService", ex); } } } OnDataChange(); }