public AsyncWebSocketClientConfiguration() { InitialBufferAllocationCount = 4; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. SslTargetHost = null; SslClientCertificates = new X509CertificateCollection(); SslEncryptionPolicy = EncryptionPolicy.RequireEncryption; SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls; SslCheckCertificateRevocation = false; SslPolicyErrorsBypassed = false; ConnectTimeout = TimeSpan.FromSeconds(10); CloseTimeout = TimeSpan.FromSeconds(5); KeepAliveInterval = TimeSpan.FromSeconds(30); KeepAliveTimeout = TimeSpan.FromSeconds(5); ReasonableFragmentSize = 4096; EnabledExtensions = new Dictionary<string, IWebSocketExtensionNegotiator>() { { PerMessageCompressionExtension.RegisteredToken, new PerMessageCompressionExtensionNegotiator() }, }; EnabledSubProtocols = new Dictionary<string, IWebSocketSubProtocolNegotiator>(); OfferedExtensions = new List<WebSocketExtensionOfferDescription>() { new WebSocketExtensionOfferDescription(PerMessageCompressionExtension.RegisteredToken), }; RequestedSubProtocols = new List<WebSocketSubProtocolRequestDescription>(); }
/// <summary> /// Close socket channel. /// </summary> /// <param name="shutdown">Pass true to gracefully close the connection.</param> private void CloseSocket(bool shutdown) { try { if (this.clientSocket != null) { if (shutdown) { this.clientSocket.Shutdown(SocketShutdown.Both); } else { LingerOption option = new LingerOption(true, 0); this.clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, option); } this.clientSocket.Close(); } } catch (Exception error) { this.btService.ReportNestedError(error); } finally { this.clientSocket = null; } }
public AsyncWebSocketServerConfiguration() { InitialBufferAllocationCount = 100; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. PendingConnectionBacklog = 200; AllowNatTraversal = true; SslEnabled = false; SslServerCertificate = null; SslEncryptionPolicy = EncryptionPolicy.RequireEncryption; SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls; SslClientCertificateRequired = true; SslCheckCertificateRevocation = false; SslPolicyErrorsBypassed = false; ConnectTimeout = TimeSpan.FromSeconds(10); CloseTimeout = TimeSpan.FromSeconds(5); KeepAliveInterval = TimeSpan.FromSeconds(60); KeepAliveTimeout = TimeSpan.FromSeconds(15); ReasonableFragmentSize = 4096; EnabledExtensions = new Dictionary<string, IWebSocketExtensionNegotiator>() { { PerMessageCompressionExtension.RegisteredToken, new PerMessageCompressionExtensionNegotiator() }, }; EnabledSubProtocols = new Dictionary<string, IWebSocketSubProtocolNegotiator>(); }
public SyncSocClient(string _ipAddress, int port, int timeout) { try { IPAddress ipAddress = System.Net.IPAddress.Parse(_ipAddress); mPort = port; remoteEP = new IPEndPoint(ipAddress, mPort); mSender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (timeout > 0) { mSender.ReceiveTimeout = timeout; mSender.SendTimeout = timeout; } //mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout); // The socket will linger for 10 seconds after Socket.Close is called. LingerOption lingerOption = new LingerOption(true, 10); mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); stateObj = new StateObject(mSender); } catch (Exception e) { SetErrorMessage(e, string.Format("소켓생성Error ip[{0}]/port[{1}]/timeout[{2}]]",_ipAddress,port,timeout)); Logger.error(e.ToString()); } }
public static Socket NewSocket() { LingerOption lo = new LingerOption(true, 10); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = true; socket.LingerState = lo; socket.ReceiveBufferSize = Const.BufferSize; socket.SendBufferSize = Const.BufferSize; return socket; }
private Thread wThread; // The local thread #endregion Fields #region Constructors public ClientManager(Socket clsock) { this.ClientSocket = clsock; this.remoteAddress = RemoteAddress.Parse(clsock.RemoteEndPoint.ToString()); LingerOption lingeroption = new LingerOption(false, 0); this.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, (Server.cfg.CTI_CLIENT_KEEPALIVE * 1000)); this.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingeroption); this.ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (Server.cfg.CTI_CLIENT_TIMEOUT * 1000)); Server.logger.WriteLine(LogType.Notice, string.Format("ClientManager initialized for {0}",clsock.RemoteEndPoint.ToString())); }
public TcpSocketSaeaClientConfiguration() { InitialBufferAllocationCount = 4; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. FrameBuilder = new SizePrefixedFrameBuilder(); }
private HttpConnectionHandler(Socket socket, RequestHandler httpProcessor) { this._socket = socket; // { LingerOption linger = new LingerOption(true, 60); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, linger); // Object langer = _socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } _httpProcessor = httpProcessor; _networkStream = new NetworkStream(_socket, FileAccess.ReadWrite, false); }
/** * 连接指定地址 */ public void Connect(string ip,int port) { this.status = STATUS_CONNECTING; this.ip = ip; this.port = port; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); LingerOption linger = new LingerOption(true,0); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, linger); clientSocket.BeginConnect(this.ip, this.port, connected, this); }
public TcpSocketSaeaServerConfiguration() { InitialBufferAllocationCount = 100; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. PendingConnectionBacklog = 200; AllowNatTraversal = true; FrameBuilder = new SizePrefixedFrameBuilder(); }
public void InitializeConnection() { isInitialized = false; isClosed = true; receivingInit(); sendingInit(); errorMessage = ""; try { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Get the remote IP address IPAddress ip = IPAddress.Parse(this.ipAddress); // Create the end point IPEndPoint ipEnd = new IPEndPoint(ip, this.port); // Connect to the remote host clientSocket.Connect(ipEnd); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); clientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); // http://msdn.microsoft.com/en-us/library/system.net.sockets.lingeroption(VS.71).aspx LingerOption myOpts = new LingerOption(true, 2); clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, myOpts); if (clientSocket.Connected) { isInitialized = true; } } catch (SocketException e) { isInitialized = false; DebuggerIX.WriteLine(DebuggerTag.Net, "[ClientInitConnection]", "Connection failed, is the server running? " + e.Message); errorMessage = e.Message; } catch (NullReferenceException e) { isInitialized = false; DebuggerIX.WriteLine(DebuggerTag.Net, "[ClientInitConnection]", "Connection failed, is the server running? " + e.Message); errorMessage = e.Message; } }
public TcpTransport(Socket socket) { // parameters validation if (socket == null) throw new ArgumentNullException("socket"); if ((socket.AddressFamily != AddressFamily.InterNetwork) || socket.ProtocolType != ProtocolType.Tcp) throw new NotSupportedException("Only TCP connections supported"); _socket = socket; // disable nagle delays _socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); // set linger option LingerOption lingerOption = new LingerOption(true, 3); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); }
// public methods public void OpenConnection() { try { reqClient = new TcpClient(); reqClient.NoDelay = false; reqClient.ReceiveTimeout = 2000; reqClient.SendTimeout = 2000; LingerOption lingerOption = new LingerOption(true, 0); reqClient.LingerState = lingerOption; reqClient.Connect(Connection.BravaIP, Connection.BravaPort); Connection.rqStream = reqClient.GetStream(); } catch (SocketException se) { throw(se); } }
public AsyncTcpSocketClientConfiguration() { InitialBufferAllocationCount = 4; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. SslEnabled = false; SslTargetHost = null; SslClientCertificates = new X509CertificateCollection(); SslEncryptionPolicy = EncryptionPolicy.RequireEncryption; SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls; SslCheckCertificateRevocation = false; SslPolicyErrorsBypassed = false; ConnectTimeout = TimeSpan.FromSeconds(15); FrameBuilder = new SizePrefixedFrameBuilder(); }
public WebSocketClientConfiguration() { InitialPooledBufferCount = 4; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. SslTargetHost = null; SslClientCertificates = new X509CertificateCollection(); SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls; SslCheckCertificateRevocation = false; SslPolicyErrorsBypassed = false; ConnectTimeout = TimeSpan.FromSeconds(10); CloseTimeout = TimeSpan.FromSeconds(5); KeepAliveInterval = TimeSpan.FromSeconds(30); KeepAliveTimeout = TimeSpan.FromSeconds(5); ReasonableFragmentSize = 4096; }
public TcpSocketServerConfiguration() { InitialPooledBufferCount = 100; ReceiveBufferSize = 8192; SendBufferSize = 8192; ReceiveTimeout = TimeSpan.Zero; SendTimeout = TimeSpan.Zero; NoDelay = true; LingerState = new LingerOption(false, 0); // The socket will linger for x seconds after Socket.Close is called. PendingConnectionBacklog = 200; AllowNatTraversal = true; SslEnabled = false; SslServerCertificate = null; SslEncryptionPolicy = EncryptionPolicy.RequireEncryption; SslEnabledProtocols = SslProtocols.Ssl3 | SslProtocols.Tls; SslClientCertificateRequired = true; SslCheckCertificateRevocation = false; SslPolicyErrorsBypassed = false; ConnectTimeout = TimeSpan.FromSeconds(15); FrameBuilder = new LengthPrefixedFrameBuilder(); }
public static unsafe SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue) { var opt = new Interop.Sys.LingerOption { OnOff = optionValue.Enabled ? 1 : 0, Seconds = optionValue.LingerTime }; Interop.Error err = Interop.Sys.SetLingerOption(handle.FileDescriptor, &opt); return err == Interop.Error.SUCCESS ? SocketError.Success : GetSocketErrorForErrorCode(err); }
public void GetSocketOption_obj_internal(SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error) { obj_val = null; error = 0; if (jSocket == null && jServerSocket == null) { error = 10022; //WSAEINVAL (Invalid argument) return; } switch (level) { case SocketOptionLevel.IPv6: error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; case SocketOptionLevel.IP: if (name != SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; } break; case SocketOptionLevel.Udp: if (name == SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) } else { error = 10022; //WSAEINVAL (Invalid argument) } return; case SocketOptionLevel.Tcp: if (name != SocketOptionName.NoDelay) { error = 10022; //WSAEINVAL (Invalid argument) return; } break; } try { bool bval = false; int ival = 0; switch (name) { case SocketOptionName.DontLinger: ival = jSocket.getSoLinger(); if (ival == -1) { obj_val = 1; } else { obj_val = 0; } break; case SocketOptionName.Linger: ival = jSocket.getSoLinger(); if (ival == -1) { ival = 0; } LingerOption ret = new LingerOption((ival != 0), ival); obj_val = ret; break; case SocketOptionName.KeepAlive: bval = jSocket.getKeepAlive(); obj_val = ((bval)?1:0); break; case SocketOptionName.NoDelay: bval = jSocket.getTcpNoDelay(); obj_val = ((bval)?1:0); break; case SocketOptionName.ReceiveBuffer: if (jServerSocket != null) { ival = jServerSocket.getReceiveBufferSize(); } else { ival = jSocket.getReceiveBufferSize(); } obj_val = ival; break; case SocketOptionName.ReceiveTimeout: if (jServerSocket != null) { ival = jServerSocket.getSoTimeout(); } else { ival = jSocket.getSoTimeout(); } obj_val = ival; break; case SocketOptionName.ReuseAddress: if (jServerSocket != null) { bval = jServerSocket.getReuseAddress(); } else { bval = jSocket.getReuseAddress(); } obj_val = ((bval)?1:0); break; case SocketOptionName.SendBuffer: ival = jSocket.getSendBufferSize(); obj_val = ival; break; case SocketOptionName.OutOfBandInline: bval = jSocket.getOOBInline(); obj_val = ((bval)?1:0); break; default: error = 10022; //WSAEINVAL (Invalid argument) break; } } catch (Exception e) { error = 10022; //WSAEINVAL (Invalid argument) obj_val = null; } }
public static unsafe SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue) { var linger = new Interop.libc.linger(); var optLen = (uint)sizeof(Interop.libc.linger); int err = Interop.libc.getsockopt(handle.FileDescriptor, Interop.libc.SOL_SOCKET, Interop.libc.SO_LINGER, &linger, &optLen); if (err == -1) { optionValue = default(LingerOption); return GetLastSocketError(); } optionValue = new LingerOption(linger.l_onoff != 0, linger.l_linger); return SocketError.Success; }
public static unsafe SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue) { var linger = new Interop.libc.linger { l_onoff = optionValue.Enabled ? 1 : 0, l_linger = optionValue.LingerTime }; int err = Interop.libc.setsockopt(handle.FileDescriptor, Interop.libc.SOL_SOCKET, Interop.libc.SO_LINGER, &linger, (uint)sizeof(Interop.libc.linger)); return err == -1 ? GetLastSocketError() : SocketError.Success; }
private LingerOption getLingerOpt() { Linger lngopt = new Linger(); int optlen = 4; // This can throw ObjectDisposedException. SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.getsockopt( m_Handle, SocketOptionLevel.Socket, SocketOptionName.Linger, out lngopt, ref optlen); GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::getLingerOpt() UnsafeNclNativeMethods.OSSOCK.getsockopt returns errorCode:" + errorCode); // // if the native call fails we'll throw a SocketException // if (errorCode==SocketError.SocketError) { // // update our internal state after this socket error and throw // SocketException socketException = new SocketException(); UpdateStatusAfterSocketError(socketException); if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "getLingerOpt", socketException); throw socketException; } LingerOption lingerOption = new LingerOption(lngopt.OnOff!=0, (int)lngopt.Time); return lingerOption; }
public void SetSocketOption_internal(SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error) { error = 0; if (byte_val != null) { error = -1; throw new NotImplementedException(); } if (jSocket == null && jServerSocket == null) { error = 10022; //WSAEINVAL (Invalid argument) return; } switch (level) { case SocketOptionLevel.IPv6: error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; case SocketOptionLevel.IP: if (name != SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; } break; case SocketOptionLevel.Udp: if (name == SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) } else { error = 10022; //WSAEINVAL (Invalid argument) } return; case SocketOptionLevel.Tcp: if (name != SocketOptionName.NoDelay) { error = 10022; //WSAEINVAL (Invalid argument) return; } break; } try { bool bval = false; int ival = 0; switch (name) { case SocketOptionName.DontLinger: jSocket.setSoLinger(false, 0); break; case SocketOptionName.Linger: LingerOption lval = obj_val as LingerOption; if (lval != null) { jSocket.setSoLinger(lval.Enabled, lval.LingerTime); } else { error = 10022; //WSAEINVAL (Invalid argument) } break; case SocketOptionName.KeepAlive: if (obj_val != null) { bval = ((int)obj_val == 0)?false:true; } else { bval = (int_val == 0)?false:true; } jSocket.setKeepAlive(bval); break; case SocketOptionName.NoDelay: if (obj_val != null) { bval = ((int)obj_val == 0)?false:true; } else { bval = (int_val == 0)?false:true; } jSocket.setTcpNoDelay(bval); break; case SocketOptionName.ReceiveBuffer: ival = int_val; if (obj_val != null) { ival = (int)obj_val; } if (jServerSocket != null) { jServerSocket.setReceiveBufferSize(ival); } else { jSocket.setReceiveBufferSize(ival); } break; case SocketOptionName.ReceiveTimeout: ival = int_val; if (obj_val != null) { ival = (int)obj_val; } if (jServerSocket != null) { jServerSocket.setSoTimeout(ival); } else { jSocket.setSoTimeout(ival); } break; case SocketOptionName.ReuseAddress: if (obj_val != null) { bval = ((int)obj_val == 0)?false:true; } else { bval = (int_val == 0)?false:true; } if (jServerSocket != null) { jServerSocket.setReuseAddress(bval); } else { jSocket.setReuseAddress(bval); } break; case SocketOptionName.SendBuffer: ival = int_val; if (obj_val != null) { ival = (int)obj_val; } jSocket.setSendBufferSize(ival); break; case SocketOptionName.OutOfBandInline: if (obj_val != null) { bval = ((int)obj_val == 0)?false:true; } else { bval = (int_val == 0)?false:true; } jSocket.setOOBInline(bval); break; default: error = 10022; //WSAEINVAL (Invalid argument) break; } } catch (Exception e) { error = 10022; //WSAEINVAL (Invalid argument) obj_val = null; } }
private void setLingerOption(LingerOption lref) { Linger lngopt = new Linger(); lngopt.OnOff = lref.Enabled ? (ushort)1 : (ushort)0; lngopt.Time = (ushort)lref.LingerTime; GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::setLingerOption(): lref:" + lref.ToString()); // This can throw ObjectDisposedException. SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.setsockopt( m_Handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lngopt, 4); GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::setLingerOption() UnsafeNclNativeMethods.OSSOCK.setsockopt returns errorCode:" + errorCode); // // if the native call fails we'll throw a SocketException // if (errorCode==SocketError.SocketError) { // // update our internal state after this socket error and throw // SocketException socketException = new SocketException(); UpdateStatusAfterSocketError(socketException); if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "setLingerOption", socketException); throw socketException; } }
public void GetSocketOption_obj_internal(SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error) { obj_val = null; error = 0; if (jSocket == null) { error = 10022; //WSAEINVAL (Invalid argument) return; } switch (level) { case SocketOptionLevel.IPv6: error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; case SocketOptionLevel.IP: if (name != SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) return; } break; case SocketOptionLevel.Udp: if (name == SocketOptionName.NoDelay) { error = 10042; //WSAENOPROTOOPT (Bad protocol option) } else { error = 10022; //WSAEINVAL (Invalid argument) } return; case SocketOptionLevel.Tcp: if (name != SocketOptionName.NoDelay) { error = 10022; //WSAEINVAL (Invalid argument) return; } break; } try { bool bval = false; int ival = 0; switch (name) { case SocketOptionName.DontLinger: ival = jSocket.getSoLinger(); if (ival == -1) { obj_val = 1; } else { obj_val = 0; } break; case SocketOptionName.Linger: ival = jSocket.getSoLinger(); if (ival == -1) { ival = 0; } LingerOption ret = new LingerOption((ival != 0), ival); obj_val = ret; break; case SocketOptionName.KeepAlive: bval = jSocket.getKeepAlive(); obj_val = ((bval)?1:0); break; case SocketOptionName.NoDelay: bval = jSocket.getTcpNoDelay(); obj_val = ((bval)?1:0); break; case SocketOptionName.ReceiveBuffer: ival = jSocket.getReceiveBufferSize(); obj_val = ival; break; case SocketOptionName.ReceiveTimeout: ival = jSocket.getSoTimeout(); obj_val = ival; break; case SocketOptionName.ReuseAddress: bval = jSocket.getReuseAddress(); obj_val = ((bval)?1:0); break; case SocketOptionName.SendBuffer: ival = jSocket.getSendBufferSize(); obj_val = ival; break; case SocketOptionName.OutOfBandInline: bval = jSocket.getOOBInline(); obj_val = ((bval)?1:0); break; default: error = 10022; //WSAEINVAL (Invalid argument) break; } } catch (Exception e) { error = 10022; //WSAEINVAL (Invalid argument) obj_val = null; } }
// --------------- Helper methods ------------------------------------ private NetworkStream GetConnection() { try { if (host == null) { host = SmtpConfig.SmtpHost; } if (port == 0) { port = SmtpConfig.SmtpPort; } if (host != null && port != 0) { tcpc = new TcpClient(host, port); LogMessage("connecting to:" + host + ":" + port, ""); tcpc.ReceiveTimeout= recieveTimeout; tcpc.SendTimeout = sendTimeout; tcpc.ReceiveBufferSize = receiveBufferSize; tcpc.SendBufferSize = sendBufferSize; LingerOption lingerOption = new LingerOption(true, 10); tcpc.LingerState = lingerOption; } else { throw new SmtpException("Cannot use SendMail() method without specifying target host and port"); } } catch(SocketException e) { throw new SmtpException("Cannot connect to specified smtp host(" + host + ":" + port + ").", e); } OnConnect(EventArgs.Empty); return tcpc.GetStream(); }
internal SocketError ReplaceHandle() { // Copy out values from key options. The copied values should be kept in sync with the // handling in SafeCloseSocket.TrackOption. Note that we copy these values out first, before // we change _handle, so that we can use the helpers on Socket which internally access _handle. // Then once _handle is switched to the new one, we can call the setters to propagate the retrieved // values back out to the new underlying socket. bool broadcast = false, dontFragment = false, noDelay = false; int receiveSize = -1, receiveTimeout = -1, sendSize = -1, sendTimeout = -1; short ttl = -1; LingerOption linger = null; if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) { dontFragment = DontFragment; } if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) { broadcast = EnableBroadcast; } if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) { linger = LingerState; } if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) { noDelay = NoDelay; } if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) { receiveSize = ReceiveBufferSize; } if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) { receiveTimeout = ReceiveTimeout; } if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) { sendSize = SendBufferSize; } if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) { sendTimeout = SendTimeout; } if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) { ttl = Ttl; } // Then replace the handle with a new one SafeCloseSocket oldHandle = _handle; SocketError errorCode = SocketPal.CreateSocket(_addressFamily, _socketType, _protocolType, out _handle); oldHandle.TransferTrackedState(_handle); oldHandle.Dispose(); if (errorCode != SocketError.Success) { return(errorCode); } // And put back the copied settings. For DualMode, we use the value stored in the _handle // rather than querying the socket itself, as on Unix stacks binding a dual-mode socket to // an IPv6 address may cause the IPv6Only setting to revert to true. if (_handle.IsTrackedOption(TrackedSocketOptions.DualMode)) { DualMode = _handle.DualMode; } if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) { DontFragment = dontFragment; } if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) { EnableBroadcast = broadcast; } if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) { LingerState = linger; } if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) { NoDelay = noDelay; } if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) { ReceiveBufferSize = receiveSize; } if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) { ReceiveTimeout = receiveTimeout; } if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) { SendBufferSize = sendSize; } if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) { SendTimeout = sendTimeout; } if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) { Ttl = ttl; } return(SocketError.Success); }
public static unsafe SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue) { var opt = new Interop.Sys.LingerOption(); Interop.Error err = Interop.Sys.GetLingerOption(handle.FileDescriptor, &opt); if (err != Interop.Error.SUCCESS) { optionValue = default(LingerOption); return GetSocketErrorForErrorCode(err); } optionValue = new LingerOption(opt.OnOff != 0, opt.Seconds); return SocketError.Success; }
public static void SettingLingerState(this Socket socket, LingerOption option) { socket.LingerState = option; }
private void SetLingerOption(LingerOption lref) { SocketError errorCode = SocketPal.SetLingerOption(_handle, lref); GlobalLog.Print("Socket#" + Logging.HashString(this) + "::setLingerOption() Interop.Winsock.setsockopt returns errorCode:" + errorCode); // Throw an appropriate SocketException if the native call fails. if (errorCode != SocketError.Success) { // Update the internal state of this socket according to the error before throwing. SocketException socketException = new SocketException((int)errorCode); UpdateStatusAfterSocketError(socketException); if (s_loggingEnabled) { Logging.Exception(Logging.Sockets, this, "setLingerOption", socketException); } throw socketException; } }
public static SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue) { Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger(); int optlen = 4; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, out lngopt, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(LingerOption); return GetLastSocketError(); } optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time); return SocketError.Success; }
/// <summary> /// Bắt đầu lắng nghe /// </summary> public void StartServer() { IPEndPoint localEP = new IPEndPoint(_localAddr, _port); _listener.Bind(localEP); _listener.Listen(10); _online = true; LingerOption lo = new LingerOption(false, 0); _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo); _listener.BeginAccept(new AsyncCallback(OnConnectRequest), _listener); }
/// <summary> /// Establish the network connection and link the network streams to Transaction object. /// </summary> public void OpenConnection() { this.Connection.Connected = false; try { reqClient = new TcpClient(); //reqClient.ExclusiveAddressUse = false; reqClient.NoDelay = true; reqClient.ReceiveTimeout = 500; // 10000 reqClient.SendTimeout = 500; // 10000 LingerOption lingerOption = new LingerOption(false, 0); // LingerOption lingerOption = new LingerOption(true, 1); reqClient.LingerState = lingerOption; reqClient.Connect(Connection.BravaIP, Connection.BravaPort); // bind the socket and get the stream object representing it. Connection.rqStream = reqClient.GetStream(); } catch (SocketException se) { throw (se); } }
void Linger (IntPtr handle) { if (!is_connected || linger_timeout <= 0) return; /* We don't want to receive any more data */ int error; Shutdown_internal (handle, SocketShutdown.Receive, out error); if (error != 0) return; int seconds = linger_timeout / 1000; int ms = linger_timeout % 1000; if (ms > 0) { /* If the other end closes, this will return 'true' with 'Available' == 0 */ Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error); if (error != 0) return; } if (seconds > 0) { LingerOption linger = new LingerOption (true, seconds); SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error); /* Not needed, we're closing upon return */ //if (error != 0) // return; } }
public void Disconnect(bool reuse) { if (Disabled) return; try { if (!disconnected) disconnected = true; else return; System.Threading.Thread.Sleep(4); Connection.Disconnect(false); Connection.Shutdown(SocketShutdown.Both); Connection.Close(); // Release the socket. //client.Shutdown(SocketShutdown.Both); //client.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), client); Connection.Disconnect(reuse); LingerOption lingerOption = new LingerOption(true, 10); Connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); } catch { Disabled = true; } }