/// <deprecated> /// Not used. For reference only. /// </deprecated> private async void StartPolling1() { while (true) { var readResult = await pipeReader.ReadAsync().ConfigureAwait(false); ReadOnlySequence <byte> buffer = readResult.Buffer; SequencePosition? position = buffer.Start; var remainingBytes = buffer.Length; var writeResult = (byte)0; while (remainingBytes > 0) { while (localStackByteCount == 0) { await _tun.executeLwipTask(() => _socket.Output()); await localStackBufLock.WaitAsync().ConfigureAwait(false); } var bytesToWriteCount = Math.Min(remainingBytes, localStackByteCount); var chunk = buffer.Slice(position.Value, bytesToWriteCount); var arr = chunk.ToArray(); var more = remainingBytes != bytesToWriteCount; writeResult = await _tun.executeLwipTask(() => _socket.Send(arr, more)); if (writeResult != 0) { OnError?.Invoke(this, writeResult); pipeReader.Complete(); return; } remainingBytes -= bytesToWriteCount; position = buffer.GetPosition(bytesToWriteCount, position.Value); Interlocked.Add(ref localStackByteCount, (int)-bytesToWriteCount); } pipeReader.AdvanceTo(position.Value, position.Value); await _tun.executeLwipTask(() => _socket.Output()); if (readResult.IsCanceled || readResult.IsCompleted || writeResult != 0) { break; } } pipeReader.Complete(); await _tun.executeLwipTask(() => _socket.Close()); Debug.WriteLine($"{TcpSocket.ConnectionCount()} connections now"); LocalDisconnected = true; OnFinished(this); CheckShutdown(); }
/** Disconnects from PLC. */ public bool Disconnect() { if (!connected) { return(false); } switch (plc) { case ControllerType.JF: case ControllerType.S7: case ControllerType.MB: case ControllerType.AB: try { if (socket != null) { socket.Close(); socket = null; } } catch (Exception e) { Console.WriteLine("Error:" + e.ToString()); return(false); } break; } connected = false; return(true); }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } Task.Run(async() => { // delay calling tcp connection close() // so that server have enough time to call close first. // This way we can push tcp Time_Wait to server side when possible. await Task.Delay(1000); proxyServer.UpdateServerConnectionCount(false); if (disposing) { Stream.Dispose(); try { TcpSocket.Close(); } catch { // ignore } } }); disposed = true; }
public void Close() { if (_socket != null) { _socket.Close(); } }
private void TearDown() { if (_clientSocket != null) { if (_clientSocket.IsConnected) { _clientSocket.Close(); } _clientSocket.Dispose(); } if (_evtSendWait != null) { _evtSendWait.Dispose(); } if (_fileSymProcessor != null) { _fileSymProcessor.Dispose(); } if (_rcvBuffer != null) { _rcvBuffer.Dispose(); } if (_sndBuffer != null) { _sndBuffer.Dispose(); } if (_filePath != null) { _filePath = null; } }
public void Disconnect() { if (mClientSocket != null) { mClientSocket.Close(); } }
private void DoChat() { NetworkStream stream = null; try { string message = string.Empty; while (true) { stream = TcpSocket.GetStream(); byte[] sizeBuf = new byte[TcpSocket.ReceiveBufferSize]; stream.Read(sizeBuf, 0, (int)TcpSocket.ReceiveBufferSize); int size = BitConverter.ToInt32(sizeBuf, 0); MemoryStream memoryStream = new MemoryStream(); while (size > 0) { byte[] buffer; if (size < TcpSocket.ReceiveBufferSize) { buffer = new byte[size]; } else { buffer = new byte[TcpSocket.ReceiveBufferSize]; } int rec = stream.Read(buffer, 0, buffer.Length); size -= rec; memoryStream.Write(buffer, 0, buffer.Length); } memoryStream.Close(); byte[] data = memoryStream.ToArray(); memoryStream.Dispose(); message = Encoding.UTF8.GetString(data); if (message == "") { throw new Exception("공백 출력 == 상대방 소켓 끊어짐"); } serverEvent.ReceiveServerLog(message); OnReceived(message, ClientList[TcpSocket].ToString(), false); } } catch (Exception ex) { serverEvent.ErrorLog("DoChat", ex.Message); if (TcpSocket != null) { OnDisconnected(TcpSocket); TcpSocket.Close(); stream.Close(); if (ThreadHandler.IsAlive == true) { ThreadHandler.Interrupt(); ThreadHandler.Abort(); } } } }
internal void HandleUpgrade(HttpServerRequest msg, TcpSocket socket, ArraySegment <byte> header) { try { if (OnUpgrade != null) { OnUpgrade.Invoke(msg, socket, header); } else { socket.Close(); } } catch { socket.Close(); } }
public void SocketCloseTest() { TcpSocket sock = new TcpSocket(); sock.Close(); Assert.DoesNotThrowAsync(() => { return(sock.ConnectAsync("localhost", 1002).AsTask()); }); }
static public int Close(IntPtr l) { try { TcpSocket self = (TcpSocket)checkSelf(l); self.Close(); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { SslSocket sslSocket = new SslSocket(socket); sslSocket.AuthenticateAsClient( address.Host, null, noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer, SslProtocols.Default); this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { SslSocket sslSocket = new SslSocket(socket); sslSocket.AuthenticateAsClient( address.Host, null, noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer, SslProtocols.Default); this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
private void DoChat() { NetworkStream stream = null; try { byte[] buffer = new byte[1024]; string message = string.Empty; int bytes = 0; while (true) { stream = TcpSocket.GetStream(); bytes = stream.Read(buffer, 0, buffer.Length); message = Encoding.Unicode.GetString(buffer, 0, bytes); if (OnReceived != null) { if (message.Substring(message.LastIndexOf("$") + 1) == "@") { OnReceived(message.Substring(0, message.LastIndexOf("$")), ClientList[TcpSocket].ToString(), true); } else { OnReceived(message.Substring(0, message.LastIndexOf("$")), ClientList[TcpSocket].ToString(), false); } } } } catch (Exception ex) { if (TcpSocket != null) { if (OnDisconnected != null) { OnDisconnected(TcpSocket); } if (ThreadHandler.IsAlive == true) { ThreadHandler.Interrupt(); ThreadHandler.Abort(); } TcpSocket.Close(); stream.Close(); } } }
private void AbortConnection(TcpSocket socket, int statusCode, string message = null) { if (socket.Writable) { var messageBytes = string.IsNullOrEmpty(message) ? BufferData.EmptyBytes : Encoding.UTF8.GetBytes(message); var msg = Encoding.UTF8.GetBytes( "HTTP/1.1 " + statusCode + " " + HttpUtility.GetHttpStatus(statusCode) + "\r\n" + "Connection: close\r\n" + "Content-type: text/html\r\n" + "Content-Length: " + messageBytes.Length + "\r\n" + "\r\n"); socket.Write(msg); socket.Write(messageBytes); } socket.Close(); }
public async Task ConnectTest() { TcpListener listener = new TcpListener(); listener.Listen(666); TcpSocket clientSock = new TcpSocket(); await clientSock.ConnectAsync("localhost", PORT); var status = listener.Accept(out TcpSocket serverSock); Assert.AreEqual(status, SocketStatus.Done); Assert.NotNull(serverSock); listener.Stop(); clientSock.Close(); serverSock.Close(); }
private void DoChat() { NetworkStream stream = null; try { byte[] buffer = new byte[1024]; string message = string.Empty; int bytes = 0; log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log_ChattingSystem.xml")); while (true) { stream = TcpSocket.GetStream(); bytes = stream.Read(buffer, 0, buffer.Length); message = Encoding.Unicode.GetString(buffer, 0, bytes); logger.Info("Recv: " + message); //받은 메시지 원문 기록 message = message.Substring(0, message.LastIndexOf("$")); if (OnReceived != null) { OnReceived(message, ClientList[TcpSocket].ToString()); } } } catch (Exception ex) { if (TcpSocket != null) { if (OnDisconnected != null) { OnDisconnected(TcpSocket); } if (ThreadHandler.IsAlive == true) { ThreadHandler.Interrupt(); ThreadHandler.Abort(); } TcpSocket.Close(); stream.Close(); } } }
/// <summary> /// Handle a HTTP Upgrade request. /// </summary> /// <param name="req"></param> /// <param name="conn"></param> public void HandleUpgrade(HttpServerRequest req, TcpSocket socket, ArraySegment <byte> head) { if (!socket.Readable || !socket.Writable) { socket.Destroy(); return; } if (OnConnection == null) { AbortConnection(socket, 400); return; } var upgrade = req.Headers["upgrade"]; var version = req.Headers["sec-websocket-version"]; if ((version != "13" && version != "8") || !string.Equals(upgrade, "websocket", StringComparison.InvariantCultureIgnoreCase)) { socket.Write(Encoding.ASCII.GetBytes( "HTTP/1.1 400 Bad Request\r\n" + "Connection: close\r\n" + "Sec-WebSocket-Version: 13, 8\r\n")); socket.Close(); return; } string acceptKey; using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) { var key = req.Headers["sec-websocket-key"]; acceptKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key + GUID))); } socket.Write(Encoding.UTF8.GetBytes( "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n")); socket.Flush(); OnConnection.Invoke(new WebSocket(socket, req, head)); }
/// <summary> /// Dispose. /// </summary> public void Dispose() { Task.Run(async() => { // delay calling tcp connection close() // so that server have enough time to call close first. // This way we can push tcp Time_Wait to server side when possible. await Task.Delay(1000); proxyServer.UpdateServerConnectionCount(false); Stream.Dispose(); try { TcpSocket.Close(); } catch { // ignore } }); }
static void Main() { var endpoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 8081); uv_init(); var watch = new PrepareWatcher(() => { //Console.WriteLine("Prepare Watcher Called"); }); watch.Start(); var server = new TcpServer((socket) => { clientcount++; socket.Stream.Write(System.Text.Encoding.ASCII.GetBytes(clientcount.ToString()), 1); if (clientcount > 5) { socket.Close(); } Console.WriteLine("Client Connected"); socket.Stream.OnRead += (data) => { Console.WriteLine("Data Recieved: {0}", System.Text.Encoding.ASCII.GetString(data, 0, data.Length)); socket.Stream.Write(data, data.Length); }; //socket.OnClose += () => { // Console.WriteLine("Client Disconnected"); //}; }); server.Listen(endpoint); var client = new TcpSocket(); client.Connect(endpoint, () => { client.Stream.OnRead += (data) => { Console.WriteLine("Client Recieved: {0}", System.Text.Encoding.ASCII.GetString(data, 0, data.Length)); watch.Stop(); watch.Dispose(); client.Close(); }; byte[] message = System.Text.Encoding.ASCII.GetBytes("Hello World\n"); client.Stream.Write(message, message.Length); }); var pipeserver = new PipeServer((socket) => { clientcount++; socket.Stream.Write(System.Text.Encoding.ASCII.GetBytes(clientcount.ToString()), 1); if (clientcount > 5) { socket.Close(); } Console.WriteLine("Pipe Client Connected"); socket.Stream.OnRead += (data) => { Console.WriteLine("Pipe Data Recieved: {0}", System.Text.Encoding.ASCII.GetString(data, 0, data.Length)); socket.Stream.Write(data, data.Length); }; //socket.OnClose += () => { // Console.WriteLine("Client Disconnected"); //}; }); pipeserver.Listen("libuv-csharp"); var pipeclient = new PipeSocket(); pipeclient.Connect("libuv-csharp", () => { pipeclient.Stream.OnRead += (data) => { Console.WriteLine("Pipe Client Recieved: {0}", System.Text.Encoding.ASCII.GetString(data, 0, data.Length)); watch.Stop(); watch.Dispose(); pipeclient.Close(); }; byte[] message = System.Text.Encoding.ASCII.GetBytes("Hello World\n"); pipeclient.Stream.Write(message, message.Length); }); var watch2 = new PrepareWatcher(() => { //Console.WriteLine("Prepare Watcher 2 Called"); }); watch2.Start(); var check = new CheckWatcher(() => { //Console.WriteLine("Check Watcher Called"); }); check.Start(); var idle = new IdleWatcher(() => { //Console.WriteLine("Idle Watcher Called"); }); idle.Start(); var after = new TimerWatcher(new TimeSpan(0, 0, 5), new TimeSpan(1, 0, 0), () => { //Console.WriteLine("After 5 Seconds"); }); after.Start(); var every = new TimerWatcher(new TimeSpan(0, 0, 5), () => { //Console.WriteLine("Every 5 Seconds"); // after.Stop(); }); every.Start(); var cp = new ChildProcess("ls"); cp.Spawn(); uv_run(); }
public void Close() { _socket.Close(); }
private void DoChat() { NetworkStream stream = null; try { string message = string.Empty; while (true) { stream = TcpSocket.GetStream(); byte[] sizeBuf = new byte[TcpSocket.ReceiveBufferSize]; stream.Read(sizeBuf, 0, (int)TcpSocket.ReceiveBufferSize); int size = BitConverter.ToInt32(sizeBuf, 0); MemoryStream ms = new MemoryStream(); while (size > 0) { byte[] buffer; if (size < TcpSocket.ReceiveBufferSize) { buffer = new byte[size]; } else { buffer = new byte[TcpSocket.ReceiveBufferSize]; } int rec = stream.Read(buffer, 0, buffer.Length); size -= rec; ms.Write(buffer, 0, buffer.Length); } ms.Close(); byte[] data = ms.ToArray(); ms.Dispose(); message = Encoding.UTF8.GetString(data); //MessageBox.Show(message); serverEvent.ReceiveServerLog(message); //받은 메시지 원문 기록 OnReceived(message, ClientList[TcpSocket].ToString(), false); /* * if (OnReceived != null) * { * if (message.Substring(message.LastIndexOf("$") + 1) == "@") * OnReceived(message.Substring(0, message.LastIndexOf("$")), ClientList[TcpSocket].ToString(), true); * else * ; * } * */ } } catch (Exception ex) { serverEvent.ErrorLog("DoChat", ex.Message); if (TcpSocket != null) { /* * ServerSecurity Encrypted = new ServerSecurity(); * * * string Encrypted = Encrypt.EncryptedMessage(IpEndPoint.Address + ":" + IpEndPoint.Port + "/" + " 연결이 종료되었습니다." * , serverEvent.LocalIPAddress() + ":" + PortNum() + "/" + ClientList[TcpSocket].ToString()); * MessageBox.Show(Encrypted); * * OnReceived(Encrypted, ClientList[TcpSocket].ToString(), true); * */ TcpSocket.Close(); stream.Close(); if (ThreadHandler.IsAlive == true) { ThreadHandler.Interrupt(); ThreadHandler.Abort(); } if (OnDisconnected != null) { OnDisconnected(TcpSocket); } } } }
public void Close() { TcpSocket?.Close(); }
public virtual void Close() { _tun.executeLwipTask(() => _socket.Close()); Debug.WriteLine($"{TcpSocket.ConnectionCount()} connections now"); }
public void TcpStop() { //enabled = false; tcpClient.Close(); tcpRuning = false; }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; // reference to SSL socket, wrapper for above TCP socket SslSocket sslSocket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); // SSL connection requested with an SSL host if (address.UseSsl) { // wrap TCP socket to SSL socket sslSocket = new SslSocket(socket, address.Host, ValidateCertificate); } socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (address.UseSsl) { if (sslSocket != null) { sslSocket.Close(); sslSocket = null; } } if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; // reference to SSL socket, wrapper for above TCP socket SslSocket sslSocket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); // SSL connection requested with an SSL host if (address.UseSsl) { // wrap TCP socket to SSL socket sslSocket = new SslSocket(socket, address.Host, ValidateCertificate); } socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (address.UseSsl) { if (sslSocket != null) { sslSocket.Close(); sslSocket = null; } } if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
private void HandleClose(int statusCode, string message) { Close((ushort)statusCode, message); _socket.Close(); }