@@ -101,6 +101,8 @@ public abstract class WebSocket : IDisposable
101101 /// The Remote Endpoint where the WebSocket connects to.
102102 /// </value>
103103 public IPEndPoint RemoteEndPoint { get ; private set ; }
104+
105+ private Socket _socket ;
104106
105107 /// <summary>
106108 /// Creates an instance of the System.Net.WebSockets.WebSocket class.
@@ -123,16 +125,17 @@ protected WebSocket( WebSocketOptions options = null)
123125 /// </summary>
124126 /// <param name="stream">The stream for the connection.</param>
125127 /// <param name="isServer"><see langword="true"/> to indicate it's the server-side of the connection; <see langword="false"/> if it's the client-side.</param>
126- /// <param name="remoteEndPoint ">The Remote Endpoint where the WebSocket connects to.</param>
127- protected void ConnectToStream ( NetworkStream stream , bool isServer , IPEndPoint remoteEndPoint )
128+ /// <param name="socket ">The socket on which the WebSocket connects to.</param>
129+ protected void ConnectToStream ( NetworkStream stream , bool isServer , Socket socket )
128130 {
129131 ReceiveStream = stream ;
130132 IsServer = isServer ;
131- RemoteEndPoint = remoteEndPoint ;
133+ _socket = socket ;
134+ RemoteEndPoint = ( IPEndPoint ) socket . RemoteEndPoint ;
132135 LastContactTimeStamp = DateTime . UtcNow ;
133136
134137 //start server sending and receiving async
135- WebSocketReceiver = new WebSocketReceiver ( stream , remoteEndPoint , this , IsServer , MaxReceiveFrameSize , OnReadError ) ;
138+ WebSocketReceiver = new WebSocketReceiver ( stream , RemoteEndPoint , this , IsServer , MaxReceiveFrameSize , OnReadError ) ;
136139 _webSocketSender = new WebSocketSender ( stream , IsServer , OnWriteError ) ;
137140
138141 ReceiveAndControllThread receiveThread = new ReceiveAndControllThread ( this ) ;
@@ -274,6 +277,7 @@ internal void RawClose(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.E
274277 {
275278 int msWaited = 0 ;
276279
280+ //Give it a moment for sending a close message. This will block the thread.
277281 while ( ! _webSocketSender . CloseMessageSent )
278282 {
279283 msWaited += 50 ;
@@ -295,7 +299,12 @@ internal void HardClose()
295299
296300 Debug . WriteLine ( $ "Connection - { RemoteEndPoint . ToString ( ) } - Closed") ;
297301
298- ConnectionClosed ? . Invoke ( this , new EventArgs ( ) ) ;
302+ ConnectionClosed ? . Invoke ( this , new EventArgs ( ) ) ;
303+
304+ //Let the tcp socket linger for a second so it can try and send all data out before final close.
305+ _socket . SetSocketOption ( SocketOptionLevel . Socket , SocketOptionName . Linger , 1 ) ;
306+
307+ _socket . Close ( ) ;
299308 }
300309
301310 internal bool QueueMessageToSend ( SendMessageFrame frame )
0 commit comments