/// <summary> /// Starts sending block of data. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> private void SendDataBlock(Stream strm, object tag, SocketCallBack callBack) { byte[] data = new byte[4000]; int countReaded = strm.Read(data, 0, data.Length); m_pSocket.BeginSend(data, 0, countReaded, 0, new AsyncCallback(OnSendedData), new object[] { strm, tag, callBack }); }
/// <summary> /// Is called from asynchronous socket if data is sended. /// </summary> /// <param name="a"></param> private static void OnSendedData(IAsyncResult a) { object[] param = (object[])a.AsyncState; BufferedSocket socket = (BufferedSocket)param[0]; MemoryStream strm = (MemoryStream)param[1]; object tag = param[2]; SocketCallBack callBack = (SocketCallBack)param[3]; try{ int countSended = socket.Socket.EndSend(a); // Send next data block if (strm.Position < strm.Length) { SendDataBlock(socket, strm, tag, callBack); } // We sended all data else { callBack(SocketCallBackResult.Ok, strm.Position, null, tag); } } catch (Exception x) { callBack(SocketCallBackResult.Exception, strm.Position, x, tag); } }
void Awake() { //Debug.Log("ServerSetting : " + serverSetting.HttpServerIp); packetHandler = this.GetComponent <PacketHandler>(); //BallManager = BallManager.instance; socketCallBack = new SocketCallBack(this); packetHandler.InitPacketHandler(socketCallBack); }
/// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line"></param> /// <param name="callBack"></param> public void BeginSendLine(string line, SocketCallBack callBack) { if (!line.EndsWith("\r\n")) { line += "\r\n"; } BeginSendData(new MemoryStream(m_pEncoding.GetBytes(line)), null, callBack); }
public _SocketState(Stream strm, long lengthToRead, long maxLength, object tag, SocketCallBack callBack) { m_pStream = strm; m_LenthToRead = lengthToRead; m_MaxLength = maxLength; m_Tag = tag; m_pCallback = callBack; m_RecvType = ReadType.Length; }
public _SocketState(Stream strm,long lengthToRead,long maxLength,object tag,SocketCallBack callBack) { m_pStream = strm; m_LenthToRead = lengthToRead; m_MaxLength = maxLength; m_Tag = tag; m_pCallback = callBack; m_RecvType = ReadType.Length; }
public _SocketState(Stream strm, long maxLength, string terminator, string removeFromEnd, object tag, SocketCallBack callBack) { m_pStream = strm; m_MaxLength = maxLength; m_RemFromEnd = removeFromEnd; m_Tag = tag; m_pCallback = callBack; m_pStack = new _FixedStack(terminator); m_RecvType = ReadType.Terminator; }
public _SocketState(Stream strm,long maxLength,string terminator,string removeFromEnd,object tag,SocketCallBack callBack) { m_pStream = strm; m_MaxLength = maxLength; m_RemFromEnd = removeFromEnd; m_Tag = tag; m_pCallback = callBack; m_pStack = new _FixedStack(terminator); m_RecvType = ReadType.Terminator; }
public void InitClient() { SocketCallBack callback = new SocketCallBack(); callback.callback += GetServerMessage; DemoCMDProcess process = new DemoCMDProcess( callback ); this.dispatcher = new SocketEventDispatcher( process ); this.client = new SocketClient(); this.client.SocketMessageReceivedFromServer += new System.EventHandler<SocketMessageReceivedFromServer>( this.OnReceiveMessageFromServer ); this.client.CreateConnectCompleted += new EventHandler<CreateConnectionAsyncArgs>( this.OnCreateConnectionComplete ); this.client.CloseHandler += new EventHandler( this.CloseHandler ); this.client.ConnectError += new EventHandler( this.ConnectError ); }
/// <summary> /// Is called from asynchronous socket if data is sended. /// </summary> /// <param name="a"></param> private void OnSendedData(IAsyncResult a) { object[] param = (object[])a.AsyncState; Stream strm = (Stream)param[0]; object tag = param[1]; SocketCallBack callBack = (SocketCallBack)param[2]; // ToDo: move to actual sendedCount. Currently strm.Position. try { int countSended = m_pSocket.EndSend(a); // Send next data block if (strm.Position < strm.Length) { SendDataBlock(strm, tag, callBack); } // We sended all data else { // Logging stuff if (m_pLogger != null) { if (strm is MemoryStream && strm.Length < 200) { MemoryStream ms = (MemoryStream)strm; m_pLogger.AddSendEntry(m_pEncoding.GetString(ms.ToArray()), strm.Length); } else { m_pLogger.AddSendEntry("Big binary, readed " + strm.Position.ToString() + " bytes.", strm.Length); } } if (callBack != null) { callBack(SocketCallBackResult.Ok, strm.Position, null, tag); } } OnActivity(); } catch (Exception x) { if (callBack != null) { callBack(SocketCallBackResult.Exception, strm.Position, x, tag); } } }
// Use this for initialization void Start() { SocketCallBack callback = new SocketCallBack(); callback.callback += GetServerMessage; DemoCMDProcess process = new DemoCMDProcess(callback); this.diapatcher = new SocketEventDispatcher(process); this.client = new SocketClient(); this.client.SocketMessageReceivedFromServer += new EventHandler <SocketMessageReceivedFromServer>(this.OnReceiveMessageFromServer); this.client.CreateConnectCompleted += new EventHandler <CreateConnectionAsyncArgs>(this.OnCreateConnectionComplete); this.client.CloseHandler += new EventHandler(this.CloseHandler); this.client.ConnectError += new EventHandler(this.ConnectError); }
/// <summary> /// 自动获取IP地址的启动函数 /// </summary> /// <param name="Port"></param> /// <param name="callBack"></param> /// <returns></returns> public int StarServer(int Port, SocketCallBack callBack) { Server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connects = new Connect[MAX_CONNECT_NUMBERS]; IPEndPoint iPEnd = new IPEndPoint(IPAddress.Any, Port); if (callBack != null) { SocketCall += callBack; } Server_Socket.Bind(iPEnd); Server_Socket.Listen(10); Server_Socket.BeginAccept(AsyncAccept, null); FDebug.Log(iPEnd.Address.ToString()); return(1); }
/// <summary> /// 自定义端口的启动函数 /// </summary> /// <param name="IP"></param> /// <param name="Port"></param> /// <param name="callBack"></param> public void StarServer(string IP, int Port, SocketCallBack callBack) { FDebug.Log("Service starting..."); Server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connects = new Connect[MAX_CONNECT_NUMBERS]; IPEndPoint iPEnd = new IPEndPoint(IPAddress.Parse(IP), Port); if (callBack != null) { SocketCall += callBack; } Server_Socket.Bind(iPEnd); Server_Socket.Listen(10); Server_Socket.BeginAccept(AsyncAccept, null); FDebug.Log("ServiceAddressIp:{0}", iPEnd.Address.ToString()); FDebug.Log("Service started Successfully!"); }
/// <summary> /// Is called from asynchronous socket if data is recieved. /// </summary> /// <param name="a"></param> private static void OnRecievedData(IAsyncResult a) { Hashtable param = (Hashtable)a.AsyncState; BufferedSocket socket = (BufferedSocket)param["socket"]; object tag = param["tag"]; SocketCallBack callBack = (SocketCallBack)param["callBack"]; SocketActivityCallback activityCallback = (SocketActivityCallback)param["activityCallback"]; byte[] buffer = (byte[])param["recieveBuffer"]; try{ // Call activity call back, if specified if (activityCallback != null) { activityCallback(tag); } // Socket is closed by session, we don't need to get data or call callback method. // This mainlty happens when session timesout and session is ended. if (!socket.IsClosed) { int countReaded = socket.EndReceive(a); if (countReaded > 0) { socket.AppendBuffer(buffer, countReaded); if (param["recieveType"].ToString() == "term") { ProccessData_Term(param); } else { ProccessData_Len(param); } } // Client disconnected else { callBack(SocketCallBackResult.SocketClosed, (long)param["readedCount"], null, tag); } } } catch (Exception x) { callBack(SocketCallBackResult.Exception, (long)param["readedCount"], x, tag); } }
private static void ProccessData_Len(Hashtable param) { BufferedSocket socket = (BufferedSocket)param["socket"]; MemoryStream strm = (MemoryStream)param["strm"]; object tag = param["tag"]; SocketCallBack callBack = (SocketCallBack)param["callBack"]; long dataAvailable = socket.AvailableInBuffer; if (dataAvailable > 0) { byte[] data = new byte[dataAvailable]; // Ensure that we don't get more data than needed !!! if (dataAvailable > ((long)param["lengthToRead"] - (long)param["readedCount"])) { data = new byte[(long)param["lengthToRead"] - (long)param["readedCount"]]; } int countRecieved = socket.ReceiveFromFuffer(data); // Increase readed count param["readedCount"] = ((long)param["readedCount"] + data.Length); if ((long)param["readedCount"] < (long)param["maxLength"]) { strm.Write(data, 0, data.Length); } // Message size exceeded, we must junk stream data. else if (strm.Length > 0) { strm.SetLength(0); } } // We got all data successfully, call EndRecieve call back if ((long)param["readedCount"] == (long)param["lengthToRead"]) { callBack(SocketCallBackResult.Ok, (long)param["readedCount"], null, tag); } else { // Recieve next bytes byte[] buff = new byte[1024]; param["recieveBuffer"] = buff; socket.BeginReceive(buff, 0, buff.Length, 0, new AsyncCallback(OnRecievedData), param); } }
/// <summary> /// Begins asynchronous recieveing. /// </summary> /// <param name="socket">Socket from where to get data.</param> /// <param name="strm">Stream where to store data.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param> /// <param name="removeFromEnd">Removes following string at end of data.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> /// <param name="activityCallback">Method to call, if data block is completed. Data is retrieved as blocks, /// for example data1 data2 ..., activity callback is called foreach data block.</param> public static void BeginRecieve(BufferedSocket socket,MemoryStream strm,long maxLength,string terminator,string removeFromEnd,object tag,SocketCallBack callBack,SocketActivityCallback activityCallback) { Hashtable param = new Hashtable(); param.Add("recieveType","term"); param.Add("socket",socket); param.Add("strm",strm); param.Add("removeFromEnd",removeFromEnd); param.Add("tag",tag); param.Add("callBack",callBack); param.Add("activityCallback",activityCallback); param.Add("stack",new _FixedStack(terminator)); param.Add("nextReadWriteLen",1); param.Add("readedCount",(long)0); param.Add("maxLength",maxLength); param.Add("recieveBuffer",new byte[0]); ProccessData_Term(param); }
public void InitClient() { _packetProcesser = new PacketProcesser(); SocketCallBack callback = new SocketCallBack(); callback.callback += GetServerMessage; SocketProcessData process = new SocketProcessData(callback); _dispatcher = new SocketEventDispatcher(process); _client = new SocketClient(); _client.RecvEventHandler += new EventHandler <RecvEvent>(this.OnRecveHandler); _client.ConnectHandler += new EventHandler <ConnectEvent>(this.OnConnectHandler); _client.CloseHandler += new EventHandler(this.OnCloseHandler); _client.ConnectErrorHandler += new EventHandler(this.OnConnectErrorHandler); _client.ReconnectHandler += new EventHandler(this.OnReconnectHandler); }
/// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line">Data line.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Callback to be called if sending ends.</param> public void BeginSendLine(string line, object tag, SocketCallBack callBack) { if (!line.EndsWith("\r\n")) { line += "\r\n"; } BeginSendData(new MemoryStream(m_pEncoding.GetBytes(line)), tag, callBack); }
/// <summary> /// Begins asynchronous recieveing. /// </summary> /// <param name="socket">Socket from where to get data.</param> /// <param name="strm">Stream where to store data.</param> /// <param name="lengthToRead">Length of data to read.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> /// <param name="activityCallback">Method to call, if data block is completed. Data is retrieved as blocks, /// for example data1 data2 ..., activity callback is called foreach data block.</param> public static void BeginRecieve(BufferedSocket socket,MemoryStream strm,long lengthToRead,long maxLength,object tag,SocketCallBack callBack,SocketActivityCallback activityCallback) { Hashtable param = new Hashtable(); param.Add("recieveType","len"); param.Add("socket",socket); param.Add("strm",strm); param.Add("lengthToRead",lengthToRead); param.Add("maxLength",maxLength); param.Add("tag",tag); param.Add("callBack",callBack); param.Add("activityCallback",activityCallback); param.Add("readedCount",(long)0); param.Add("recieveBuffer",new byte[0]); ProccessData_Len(param); }
/// <summary> /// Tries to read line from socket data buffer. If buffer doesn't contain line, /// next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="callback">The method to be called when the asynchronous line read operation is completed.</param> /// <param name="tag">User data.</param> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLineLength">Specifies maximum line legth.</param> /// <param name="lastByte">Last byte what was readed pevious method call or -1 if first method call.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> private void TryToReadLine(SocketCallBack callback,object tag,Stream stream,int maxLineLength,int lastByte,int readedCount) { // There is no data in buffer, buffer next block asynchronously. if(m_AvailableInBuffer == 0){ BeginBufferDataBlock(this.OnBeginReadLineBufferingCompleted,new object[]{callback,tag,stream,maxLineLength,lastByte,readedCount}); return; } // Delay last byte writing, this is because CR, if next is LF, then skip CRLF and terminate reading. // This is first method call, buffer 1 byte if(lastByte == -1){ lastByte = ReadByte(); readedCount++; // We use last byte, buffer next block asynchronously. if(m_AvailableInBuffer == 0){ BeginBufferDataBlock(this.OnBeginReadLineBufferingCompleted,new object[]{callback,tag,stream,maxLineLength,lastByte,readedCount}); return; } } int currentByte = ReadByte(); readedCount++; while(currentByte > -1){ // We got line if(lastByte == (byte)'\r' && currentByte == (byte)'\n'){ // Logging stuff if(m_pLogger != null){ if(stream.CanSeek && stream.Length < 200){ byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData,0,readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData),readedCount); } else{ m_pLogger.AddReadEntry("Big binary line, readed " + readedCount.ToString() + " bytes.",readedCount); } } // Maximum allowed length exceeded if(readedCount > maxLineLength){ if(callback != null){ callback(SocketCallBackResult.LengthExceeded,0,new ReadException(ReadReplyCode.LengthExceeded,"Maximum allowed data length exceeded !"),tag); } } // Line readed ok, call callback. if(callback != null){ callback(SocketCallBackResult.Ok,readedCount,null,tag); } return; } else{ // Maximum allowed length exceeded, just don't store data. if(readedCount < maxLineLength){ stream.WriteByte((byte)lastByte); } } // Read next byte lastByte = currentByte; if(m_AvailableInBuffer > 0){ currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else{ BeginBufferDataBlock(this.OnBeginReadLineBufferingCompleted,new object[]{callback,tag,stream,maxLineLength,lastByte,readedCount}); return; } } // We should not reach there, if so then socket closed // Logging stuff if(m_pLogger != null){ m_pLogger.AddTextEntry("Remote host closed socket !"); } if(callback != null){ callback(SocketCallBackResult.SocketClosed,0,new ReadException(ReadReplyCode.SocketClosed,"Connected host closed socket, read line terminated unexpectedly !"),tag); } }
/// <summary> /// Tries to read specified length of data from socket data buffer. If buffer doesn't contain data, /// next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="lengthToRead">Specifies number of bytes to read from socket.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> private void TryToReadReadSpecifiedLength(Stream stream,int lengthToRead,object tag,SocketCallBack callback,int readedCount) { if(lengthToRead == 0){ // Data readed ok, call callback. if(callback != null){ callback(SocketCallBackResult.Ok,readedCount,null,tag); } return; } // There is no data in buffer, buffer next block asynchronously. if(m_AvailableInBuffer == 0){ BeginBufferDataBlock(this.OnBeginReadSpecifiedLengthBufferingCompleted,new object[]{callback,tag,stream,lengthToRead,readedCount}); return; } // Buffer has less data than that we need int lengthLeftForReading = lengthToRead - readedCount; if(lengthLeftForReading > m_AvailableInBuffer){ stream.Write(m_Buffer,m_OffsetInBuffer,m_AvailableInBuffer); stream.Flush(); readedCount += m_AvailableInBuffer; // We used buffer directly, sync buffer info !!! m_OffsetInBuffer = 0; m_AvailableInBuffer = 0; BeginBufferDataBlock(this.OnBeginReadSpecifiedLengthBufferingCompleted,new object[]{callback,tag,stream,lengthToRead,readedCount}); } // Buffer contains all data we need else{ stream.Write(m_Buffer,m_OffsetInBuffer,lengthLeftForReading); stream.Flush(); readedCount += lengthLeftForReading; // We used buffer directly, sync buffer info !!! m_OffsetInBuffer += lengthLeftForReading; m_AvailableInBuffer -= lengthLeftForReading; // Logging stuff if(m_pLogger != null){ if(stream.CanSeek && stream.Length < 200){ byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData,0,readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData),lengthToRead); } else{ m_pLogger.AddReadEntry("Big binary data, readed " + readedCount + " bytes.",readedCount); } } // Data readed ok, call callback. if(callback != null){ callback(SocketCallBackResult.Ok,readedCount,null,tag); } } }
/// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="lengthToRead">Length of data to read.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm, long lengthToRead, long maxLength, object tag, SocketCallBack callBack) { _SocketState state = new _SocketState(strm, lengthToRead, maxLength, tag, callBack); ProccessData_Len(state); }
/// <summary> /// Starts reading line from socket asynchronously. /// </summary> /// <param name="strm">Stream where to store line.</param> /// <param name="maxLength">Maximum line length.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadLine(Stream strm, long maxLength, object tag, SocketCallBack callBack) { BeginReadData(strm, maxLength, "\r\n", "\r\n", tag, callBack); }
private static void ProccessData_Term(Hashtable param) { BufferedSocket socket = (BufferedSocket)param["socket"]; MemoryStream strm = (MemoryStream)param["strm"]; string removeFromEnd = (string)param["removeFromEnd"]; _FixedStack stack = (_FixedStack)param["stack"]; int nextReadWriteLen = (int)param["nextReadWriteLen"]; object tag = param["tag"]; SocketCallBack callBack = (SocketCallBack)param["callBack"]; while (nextReadWriteLen > 0) { // We used buffer, request more data if (socket.AvailableInBuffer < nextReadWriteLen) { // Store nextReadWriteLen for next call of this command param["nextReadWriteLen"] = nextReadWriteLen; // Recieve next bytes byte[] buff = new byte[1024]; param["recieveBuffer"] = buff; socket.BeginReceive(buff, 0, buff.Length, 0, new AsyncCallback(OnRecievedData), param); // End this method, if data arrives, this method is called again return; } //Read byte(s) byte[] b = new byte[nextReadWriteLen]; int countRecieved = socket.ReceiveFromFuffer(b); // Increase readed count param["readedCount"] = ((long)param["readedCount"] + countRecieved); // Write byte(s) to buffer, if length isn't exceeded. if ((long)param["readedCount"] < (long)param["maxLength"]) { strm.Write(b, 0, countRecieved); } // Message size exceeded, we must junk stream data. else if (strm.Length > 0) { strm.SetLength(0); } // Write to stack(terminator checker) nextReadWriteLen = stack.Push(b, countRecieved); } // If we reach so far, then we have successfully readed data if ((long)param["readedCount"] < (long)param["maxLength"]) { // Remove "removeFromEnd" from end if (removeFromEnd.Length > 0 && strm.Length > removeFromEnd.Length) { strm.SetLength(strm.Length - removeFromEnd.Length); } strm.Position = 0; // We got all data successfully, call EndRecieve call back callBack(SocketCallBackResult.Ok, (long)param["readedCount"], null, tag); } else { callBack(SocketCallBackResult.LengthExceeded, (long)param["readedCount"], null, tag); } }
public DemoCMDProcess(SocketCallBack Callback) { this.buffer = new byte[packetMaxLength]; this.mCallback = Callback; }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(Stream strm, object tag, SocketCallBack callBack) { SendDataBlock(strm, tag, callBack); }
/// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param> /// <param name="removeFromEnd">Removes following string at end of data.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm, long maxLength, string terminator, string removeFromEnd, object tag, SocketCallBack callBack) { _SocketState state = new _SocketState(strm, maxLength, terminator, removeFromEnd, tag, callBack); ProccessData_Term(state); }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="data">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(string data, object tag, SocketCallBack callBack) { BeginSendData(new MemoryStream(m_pEncoding.GetBytes(data)), tag, callBack); }
/// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="lengthToRead">Length of data to read.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm, long lengthToRead, long maxLength, object tag, SocketCallBack callBack) { _SocketState state = new _SocketState(strm, lengthToRead, maxLength, tag, callBack); ProccessData_Len(state); }
/// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param> /// <param name="removeFromEnd">Removes following string at end of data.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm, long maxLength, string terminator, string removeFromEnd, object tag, SocketCallBack callBack) { _SocketState state = new _SocketState(strm, maxLength, terminator, removeFromEnd, tag, callBack); ProccessData_Term(state); }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="socket">Socket where to send data.</param> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public static void BeginSend(BufferedSocket socket,Stream strm,object tag,SocketCallBack callBack) { SendDataBlock(socket,strm,tag,callBack); }
/// <summary> /// Begins reading line from socket asynchrounously. /// If maximum allowed line length is exceeded line is read to end, but isn't stored to buffer and exception /// is thrown after line reading. /// </summary> /// <param name="stream">Stream where to store readed line.</param> /// <param name="maxLineLength">Maximum line length in bytes.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous line read operation is completed.</param> public void BeginReadLine(Stream stream,int maxLineLength,object tag,SocketCallBack callback) { TryToReadLine(callback,tag,stream,maxLineLength,-1,0); }
/// <summary> /// Starts sending block of data. /// </summary> /// <param name="socket">Socket where to send data.</param> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> private static void SendDataBlock(BufferedSocket socket,Stream strm,object tag,SocketCallBack callBack) { byte[] data = new byte[1024]; int countReaded = strm.Read(data,0,data.Length); socket.Socket.BeginSend(data,0,countReaded,0,new AsyncCallback(OnSendedData),new object[]{socket,strm,tag,callBack}); }
/// <summary> /// Begins reading specified amount of data from socket asynchronously. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="lengthToRead">Specifies number of bytes to read from socket.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> public void BeginReadSpecifiedLength(Stream stream,int lengthToRead,object tag,SocketCallBack callback) { TryToReadReadSpecifiedLength(stream,lengthToRead,tag,callback,0); }
/// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line">Data line.</param> /// <param name="callBack">Callback to be called if sending ends.</param> public void BeginSendLine(string line, SocketCallBack callBack) { BeginSendLine(line, null, callBack); }
/// <summary> /// Begins specified line sending to socket asynchronously. /// </summary> /// <param name="line">Line to send.</param> /// <param name="callback">The method to be called when the asynchronous line write operation is completed.</param> public void BeginWriteLine(string line,SocketCallBack callback) { // Don't allow to wait after we send data, because there won't no more data m_pSocket.NoDelay = true; BeginWriteLine(line,null,callback); }
public DemoCMDProcess(SocketCallBack Callback) { this.buffer = new byte[packetMaxLength]; this.mCallback = Callback; }
/// <summary> /// Begins writing period terminated data to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "<CRLF>.<CRLF>". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="stream">Stream which data to write. Reading begins from stream current position and is readed to EOS.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWritePeriodTerminated(Stream stream,object tag,SocketCallBack callback) { BeginWritePeriodTerminated(stream,false,tag,callback); }
/// <summary> /// Starts sending data block to socket. /// </summary> /// <param name="stream">Stream which data to write.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="countSent">Specifies how many data is sent.</param> private void BeginProcessingWrite(Stream stream,object tag,SocketCallBack callback,int countSent) { byte[] buffer = new byte[4000]; int readedCount = stream.Read(buffer,0,buffer.Length); // There data to send if(readedCount > 0){ countSent += readedCount; m_WrittenCount += readedCount; if(m_SSL){ m_pSslStream.BeginWrite(buffer,0,readedCount,new AsyncCallback(this.OnBeginWriteCallback),new object[]{stream,tag,callback,countSent}); } else{ m_pSocketStream.BeginWrite(buffer,0,readedCount,new AsyncCallback(this.OnBeginWriteCallback),new object[]{stream,tag,callback,countSent}); } } // We have sent all data else{ // Logging stuff if(m_pLogger != null){ if(stream.CanSeek && stream.Length < 200){ byte[] sentData = new byte[stream.Length]; stream.Position = 0; stream.Read(sentData,0,sentData.Length); m_pLogger.AddSendEntry(m_pEncoding.GetString(sentData),countSent); } else{ m_pLogger.AddSendEntry("Big binary data, sent " + countSent.ToString() + " bytes.",countSent); } } // Line sent ok, call callback. if(callback != null){ callback(SocketCallBackResult.Ok,countSent,null,tag); } } }
public void InitPacketHandler(SocketCallBack scb) { socketCallBack = scb; }
/// <summary> /// Tries to read period terminated data from socket data buffer. If buffer doesn't contain /// period terminated data,next buffer data block is getted asynchronously and this method is called again. /// </summary> /// <param name="callback">The method to be called when the asynchronous period terminated read operation is completed.</param> /// <param name="tag">User data.</param> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLength">Specifies maximum data legth in bytes.</param> /// <param name="readedCount">Specifies count of bytes readed.</param> /// <param name="lastByte">Last byte what was readed pevious method call or -1 if first method call.</param> /// <param name="lineBreak">Specifies if there is active line break.</param> /// <param name="expectCRLF">Specifies if terminating CRLF is expected.</param> private void TryToReadPeriodTerminated(SocketCallBack callback,object tag,Stream stream,int maxLength,int lastByte,int readedCount,bool lineBreak,bool expectCRLF) { /* When a line of text is received by the server, it checks the line. If the line is composed of a single period, it is treated as the end of data indicator. If the first character is a period and there are other characters on the line, the first character is deleted. */ // There is no data in buffer, buffer next block asynchronously. if(m_AvailableInBuffer == 0){ BeginBufferDataBlock(this.OnBeginReadPeriodTerminatedBufferingCompleted,new object[]{callback,tag,stream,maxLength,lastByte,readedCount,lineBreak,expectCRLF}); return; } // Delay last byte writing, this is because CR, if next is LF, then last byte isn't written. // This is first method call, buffer 1 byte if(lastByte == -1){ lastByte = ReadByte(); readedCount++; // We used last byte, buffer next block asynchronously. if(m_AvailableInBuffer == 0){ BeginBufferDataBlock(this.OnBeginReadPeriodTerminatedBufferingCompleted,new object[]{callback,tag,stream,maxLength,lastByte,readedCount,lineBreak,expectCRLF}); return; } } byte[] buffer = new byte[8000]; int positionInBuffer = 0; int currentByte = ReadByte(); readedCount++; while(currentByte > -1){ // We got <CRLF> + 1 char, we must skip that char if it is '.'. if(lineBreak){ lineBreak = false; // We must skip this char if it is '.' if(currentByte == '.'){ expectCRLF = true; // Read next byte if(m_AvailableInBuffer > 0){ currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else{ // There is data in buffer, flush it if(positionInBuffer > 0){ stream.Write(buffer,0,positionInBuffer); positionInBuffer = 0; } BeginBufferDataBlock(this.OnBeginReadPeriodTerminatedBufferingCompleted,new object[]{callback,tag,stream,maxLength,lastByte,readedCount,lineBreak,expectCRLF}); return; } } } // We got <CRLF> else if(lastByte == (byte)'\r' && currentByte == (byte)'\n'){ lineBreak = true; // We have <CRLF>.<CRLF>, skip last <CRLF>. if(expectCRLF){ // There is data in buffer, flush it if(positionInBuffer > 0){ stream.Write(buffer,0,positionInBuffer); positionInBuffer = 0; } // Logging stuff if(m_pLogger != null){ if(stream.CanSeek && stream.Length < 200){ byte[] readedData = new byte[stream.Length]; stream.Position = 0; stream.Read(readedData,0,readedData.Length); m_pLogger.AddReadEntry(m_pEncoding.GetString(readedData),readedCount); } else{ m_pLogger.AddReadEntry("Big binary data, readed " + readedCount.ToString() + " bytes.",readedCount); } } // Maximum allowed length exceeded if(readedCount > maxLength){ if(callback != null){ callback(SocketCallBackResult.LengthExceeded,0,new ReadException(ReadReplyCode.LengthExceeded,"Maximum allowed data length exceeded !"),tag); } return; } // Data readed ok, call callback. if(callback != null){ callback(SocketCallBackResult.Ok,readedCount,null,tag); } return; } } // current char isn't CRLF part, so it isn't <CRLF>.<CRLF> terminator. if(expectCRLF && !(currentByte == (byte)'\r' || currentByte == (byte)'\n')){ expectCRLF = false; } // Maximum allowed length exceeded, just don't store data. if(readedCount < maxLength){ // Buffer is filled up, write buffer to stream if(positionInBuffer > (buffer.Length - 2)){ stream.Write(buffer,0,positionInBuffer); positionInBuffer = 0; } buffer[positionInBuffer] = (byte)lastByte; positionInBuffer++; } // Read next byte lastByte = currentByte; if(m_AvailableInBuffer > 0){ currentByte = ReadByte(); readedCount++; } // We have use all data in the buffer, buffer next block asynchronously. else{ // There is data in buffer, flush it if(positionInBuffer > 0){ stream.Write(buffer,0,positionInBuffer); positionInBuffer = 0; } BeginBufferDataBlock(this.OnBeginReadPeriodTerminatedBufferingCompleted,new object[]{callback,tag,stream,maxLength,lastByte,readedCount,lineBreak,expectCRLF}); return; } } // We should never reach here. if(callback != null){ callback(SocketCallBackResult.Exception,0,new Exception("Never should reach there ! method TryToReadPeriodTerminated out of while loop."),tag); } }
public SocketProcessData(SocketCallBack Callback) { this.mCallback = Callback; }
/// <summary> /// Default constructor. /// </summary> /// <param name="stream">Source stream.</param> /// <param name="closeStream">Specifies if stream must be closed after reading is completed.</param> /// <param name="tag">User data.</param> /// <param name="callback">Callback what to call if asynchronous data writing completes.</param> public _BeginWritePeriodTerminated_State(Stream stream,bool closeStream,object tag,SocketCallBack callback) { m_Stream = stream; m_CloseStream = closeStream; m_Tag = tag; m_Callback = callback; m_HasCRLF = false; m_LastByte = -1; m_CountSent = 0; }
/// <summary> /// Starts reading line from socket asynchronously. /// </summary> /// <param name="strm">Stream where to store line.</param> /// <param name="maxLength">Maximum line length.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadLine(Stream strm, long maxLength, object tag, SocketCallBack callBack) { BeginReadData(strm, maxLength, "\r\n", "\r\n", strm, callBack); }
/// <summary> /// Begins reading period terminated data. The data is terminated by a line containing only a period, that is, /// the character sequence "<CRLF>.<CRLF>". /// When a line of text is received, it checks the line. If the line is composed of a single period, /// it is treated as the end of data indicator. If the first character is a period and there are /// other characters on the line, the first character is deleted. /// If maximum allowed data length is exceeded data is read to end, but isn't stored to stream and exception /// is thrown after data reading. /// </summary> /// <param name="stream">Stream where to store readed data.</param> /// <param name="maxLength">Maximum data length in bytes.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous read operation is completed.</param> public void BeginReadPeriodTerminated(Stream stream,int maxLength,object tag,SocketCallBack callback) { TryToReadPeriodTerminated(callback,tag,stream,maxLength,-1,0,false,false); }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="socket">Socket where to send data.</param> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public static void BeginSend(BufferedSocket socket, Stream strm, object tag, SocketCallBack callBack) { SendDataBlock(socket, strm, tag, callBack); }
/// <summary> /// Begins writing specified data to socket. /// </summary> /// <param name="stream">Stream which data to write to socket. Reading starts from stream current position and will be readed to EOS.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWrite(Stream stream,object tag,SocketCallBack callback) { // Allow socket to optimise sends m_pSocket.NoDelay = false; BeginProcessingWrite(stream,tag,callback,0); }
/// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line">Data line.</param> /// <param name="callBack">Callback to be called if sending ends.</param> public void BeginSendLine(string line, SocketCallBack callBack) { BeginSendLine(line, null, callBack); }
/// <summary> /// Begins specified line sending to socket asynchronously. /// </summary> /// <param name="line">Line to send.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous line write operation is completed.</param> public void BeginWriteLine(string line,object tag,SocketCallBack callback) { // Don't allow to wait after we send data, because there won't no more data m_pSocket.NoDelay = true; if(!line.EndsWith("\r\n")){ line += "\r\n"; } byte[] lineBytes = m_pEncoding.GetBytes(line); if(m_SSL){ m_pSslStream.BeginWrite(lineBytes,0,lineBytes.Length,this.OnBeginWriteLineCallback,new object[]{tag,callback,lineBytes}); } else{ m_pSocketStream.BeginWrite(lineBytes,0,lineBytes.Length,this.OnBeginWriteLineCallback,new object[]{tag,callback,lineBytes}); } }
/// <summary> /// Starts sending block of data. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> private void SendDataBlock(Stream strm, object tag, SocketCallBack callBack) { byte[] data = new byte[4000]; int countReaded = strm.Read(data, 0, data.Length); m_pSocket.BeginSend(data, 0, countReaded, 0, new AsyncCallback(OnSendedData), new object[] { strm, tag, callBack }); }
/// <summary> /// Begins writing period terminated data to socket. The data is terminated by a line containing only a period, that is, /// the character sequence "<CRLF>.<CRLF>". Before sending a line of text, check the first /// character of the line.If it is a period, one additional period is inserted at the beginning of the line. /// </summary> /// <param name="stream">Stream which data to write. Reading begins from stream current position and is readed to EOS.</param> /// <param name="closeStream">Specifies if stream is closed after write operation has completed.</param> /// <param name="tag">User data.</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed.</param> public void BeginWritePeriodTerminated(Stream stream,bool closeStream,object tag,SocketCallBack callback) { // Allow socket to optimise sends m_pSocket.NoDelay = false; _BeginWritePeriodTerminated_State state = new _BeginWritePeriodTerminated_State(stream,closeStream,tag,callback); BeginProcessingWritePeriodTerminated(state); }
/// <summary> /// Begins asynchronous recieveing. /// </summary> /// <param name="socket">Socket from where to get data.</param> /// <param name="strm">Stream where to store data.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param> /// <param name="removeFromEnd">Removes following string at end of data.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> /// <param name="activityCallback">Method to call, if data block is completed. Data is retrieved as blocks, /// for example data1 data2 ..., activity callback is called foreach data block.</param> public static void BeginRecieve(BufferedSocket socket, MemoryStream strm, long maxLength, string terminator, string removeFromEnd, object tag, SocketCallBack callBack, SocketActivityCallback activityCallback) { Hashtable param = new Hashtable(); param.Add("recieveType", "term"); param.Add("socket", socket); param.Add("strm", strm); param.Add("removeFromEnd", removeFromEnd); param.Add("tag", tag); param.Add("callBack", callBack); param.Add("activityCallback", activityCallback); param.Add("stack", new _FixedStack(terminator)); param.Add("nextReadWriteLen", 1); param.Add("readedCount", (long)0); param.Add("maxLength", maxLength); param.Add("recieveBuffer", new byte[0]); ProccessData_Term(param); }
/// <summary> /// Begins asynchronous recieveing. /// </summary> /// <param name="socket">Socket from where to get data.</param> /// <param name="strm">Stream where to store data.</param> /// <param name="lengthToRead">Length of data to read.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> /// <param name="activityCallback">Method to call, if data block is completed. Data is retrieved as blocks, /// for example data1 data2 ..., activity callback is called foreach data block.</param> public static void BeginRecieve(BufferedSocket socket, MemoryStream strm, long lengthToRead, long maxLength, object tag, SocketCallBack callBack, SocketActivityCallback activityCallback) { Hashtable param = new Hashtable(); param.Add("recieveType", "len"); param.Add("socket", socket); param.Add("strm", strm); param.Add("lengthToRead", lengthToRead); param.Add("maxLength", maxLength); param.Add("tag", tag); param.Add("callBack", callBack); param.Add("activityCallback", activityCallback); param.Add("readedCount", (long)0); param.Add("recieveBuffer", new byte[0]); ProccessData_Len(param); }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="data">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(string data, object tag, SocketCallBack callBack) { BeginSendData(new MemoryStream(m_pEncoding.GetBytes(data)), tag, callBack); }
/// <summary> /// Starts sending block of data. /// </summary> /// <param name="socket">Socket where to send data.</param> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> private static void SendDataBlock(BufferedSocket socket, Stream strm, object tag, SocketCallBack callBack) { byte[] data = new byte[1024]; int countReaded = strm.Read(data, 0, data.Length); socket.Socket.BeginSend(data, 0, countReaded, 0, new AsyncCallback(OnSendedData), new object[] { socket, strm, tag, callBack }); }
/// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(Stream strm, object tag, SocketCallBack callBack) { SendDataBlock(strm, tag, callBack); }