public TCPSession GetSession(out int sid) { lock (_syncObject) { int idx = 0; for (; idx < _maxConnections; idx++) { if (!_busy[idx]) { _busy[idx] = true; //set busy break; } } sid = idx; if (sid >= _maxConnections) { //no enought idle session throw new ConnectionsOverflowException(); } if (_sessions[sid] == null) { _sessions[sid] = new TCPSession(_endPoint, _timeout); //this may raise socket connection refuse exception } return(_sessions[sid]); } }
public void ReleaseAndDisposeSession(int sid) { lock (_syncObject) { _busy[sid] = false; //release TCPSession session = _sessions[sid]; if (session != null) { session.Dispose(); _sessions[sid] = null; } } }
public HttpResponseHeader Send( string serverEndPoint, HttpRequestHeader header, byte[] bodyData, out byte[] responseData) { SessionCollection col = null; for (int idx = 0; idx < _servers.Count; idx++) { if (_servers[idx].Key == serverEndPoint) { col = _servers[idx].Value; break; } } if (col == null) { throw new InvalidOperationException("The specify server endpoint not found"); } bool reconnected = false; while (true) { int sid = 0; try { TCPSession session = col.GetSession(out sid); HttpResponseHeader response = session.Send(header, bodyData, out responseData); col.ReleaseSession(sid); return(response); } catch (ConnectionsOverflowException ex) { //no enought idle session //TODO:: logger throw ex; } catch (SocketException ex) { col.ReleaseAndDisposeSession(sid); //release session and dispose it if (ex.SocketErrorCode == SocketError.ConnectionAborted || ex.SocketErrorCode == SocketError.ConnectionReset) { if (reconnected) { throw ex; } else { //need re-connect, and try once again reconnected = true; continue; } } else { throw ex; } } catch (InvalidDataException ex) { col.ReleaseAndDisposeSession(sid); //release session and dispose it if (reconnected) { throw ex; } else { //need re-connect, and try once again reconnected = true; continue; } } catch (Exception ex) { col.ReleaseAndDisposeSession(sid); //release session and dispose it throw ex; } } }