private void OnDataReceived(IAsyncResult asyn) { try { if (_isClosed) { SocketLogMgt.SetLog(SocketLogType.Warning, this, "Data received, but the socket is closed."); return; } int bytesRead = _socket.EndReceive(asyn); //------------Handle Multi-byte Charactor------------- //Buffer all the bytes received and then decode this bytes at one time. //in order to support multi byte charactor set (for example: utf-8) //However, ASCII or GB or BIG5 or Unicode are easy, //we can decode even bytes at each time. List <BufferWrapper> bufferList = new List <BufferWrapper>(); //---------------------------------------------------- do { bytesRead = _socket.Receive(_buffer); SocketLogMgt.SetLog(this, _strSocketID + "Receive succeeded. " + bytesRead.ToString() + " bytes."); UpdateActiveDT(); //------------Handle Multi-byte Charactor------------- bufferList.Add(BufferWrapper.Create(_buffer, bytesRead)); //foreach (BufferWrapper w in bufferList) SocketLogMgt.SetLog(">>>>>>>>>>>> " + w.Buffer.Length.ToString()); //---------------------------------------------------- if (bytesRead > 0) { //No matter how to cut the buffer, ASCII charactor can always be decoded properly, //therefore we can use this segment to detect whether an ASCII charactor ending sign (for example "</XMLRequestMessage>") is received. //See class XmlTest.FormCoding for unit test. string str = _server.Encoder.GetString(_buffer, 0, bytesRead); _sb.Append(str); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, _strSocketID + ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, str); SocketLogMgt.SetLog(this, "------------------------"); } string receiveData = _sb.ToString(); if (SocketHelper.FindBlockEnding(receiveData)) { string sendData = null; //------------Handle Multi-byte Charactor------------- receiveData = BufferWrapper.GetString(_server.Encoder, bufferList); bufferList.Clear(); //---------------------------------------------------- receiveData = SocketHelper.UnpackMessageBlock(receiveData); _server.NotifyRequest(receiveData, ref sendData); ResponseData(sendData); //// if allow multiple session per connection, then continue receiving till connection is closed by the client. //if (_server.Config.AllowMultipleSessionPerConnection) // continue; //else // break; continue; } } }while (bytesRead > 0); // if(bytesRead==0) which means the connection is closed by the client, we will close the worker socket. SocketLogMgt.SetLog(this, "Stop receiving data because the connection is closed by the client."); CloseWorker(); } catch (SocketException err) { //needToContinue = false; SocketLogMgt.SetLastError(err); // if client does not send data in some period of time and the connection will be expired // (controled by the lower levels, and this exception occurs when the client send message again after the connection expired) // or other network exception when receiving data, then close the server socket. CloseWorker(); } catch (Exception e) { SocketLogMgt.SetLastError(e); // if communication is ok, but process message failed, do not need to close connection. } }
private void OnDataReceived(IAsyncResult asyn) { try { int bytesRead = _socket.EndReceive(asyn); //------------Handle Multi-byte Charactor------------- //Buffer all the bytes received and then decode this bytes at one time. //in order to support multi byte charactor set (for example: utf-8) //However, ASCII or GB or BIG5 or Unicode are easy, //we can decode even bytes at each time. List <BufferWrapper> bufferList = new List <BufferWrapper>(); //---------------------------------------------------- do { bytesRead = _socket.Receive(_buffer); SocketLogMgt.SetLog(this, _strSocketID + "Receive succeeded. " + bytesRead.ToString() + " bytes."); UpdateActiveDT(); //------------Handle Multi-byte Charactor------------- bufferList.Add(BufferWrapper.Create(_buffer, bytesRead)); //foreach (BufferWrapper w in bufferList) SocketLogMgt.SetLog(">>>>>>>>>>>> " + w.Buffer.Length.ToString()); //---------------------------------------------------- if (bytesRead > 0) { //No matter how to cut the buffer, ASCII charactor can always be decoded properly, //therefore we can use this segment to detect whether an ASCII charactor ending sign (for example "</XMLRequestMessage>") is received. //See class XmlTest.FormCoding for unit test. string str = _server.Encoder.GetString(_buffer, 0, bytesRead); _sb.Append(str); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, _strSocketID + ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, str); SocketLogMgt.SetLog(this, "------------------------"); } string receiveData = _sb.ToString(); if (SocketHelper.FindBlockEnding(receiveData)) { string sendData = null; //------------Handle Multi-byte Charactor------------- receiveData = BufferWrapper.GetString(_server.Encoder, bufferList); bufferList.Clear(); //---------------------------------------------------- receiveData = SocketHelper.UnpackMessageBlock(receiveData); _server.NotifyRequest(receiveData, ref sendData); ResponseData(sendData); break; } } }while (bytesRead > 0); } catch (Exception e) { SocketLogMgt.SetLastError(e); // if communication is ok, but process message failed, do not need to close connection. } }
private SocketResult Send(SocketClientConfig config, string content) { SocketLogMgt.SetLog(this, "============================================="); SocketLogMgt.SetLog(this, ": Send Data Begin."); try { Socket socket = Connect(config); if (socket == null) { return(SocketResult.Disconnect); // failed to connect to remote server } string strSend = SocketHelper.PackMessageBlock(content); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data to be sent."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strSend); SocketLogMgt.SetLog(this, "------------------------"); } Byte[] bytesSent = null; System.Text.Encoding encoder = GetEncoder(); if (encoder != null) { bytesSent = encoder.GetBytes(strSend); } if (bytesSent == null) { SocketLogMgt.SetLog(SocketLogType.Error, this, _socketID + "Encode data failed."); return(SocketResult.SendFailed); // failed to encoding outgoing message } _allDone.Reset(); SocketLogMgt.SetLog(this, _socketID + "Send data."); socket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(OnDataSent), null); bool rec = true; string strReceived = null; StringBuilder sb = new StringBuilder(); Byte[] bytesReceived = new Byte[config.ReceiveResponseBufferSizeKB * 1024]; while (rec) { if (!socket.Connected) { SocketLogMgt.SetLog(SocketLogType.Warning, this, _socketID + "Connection closed."); break; } SocketLogMgt.SetLog(this, _socketID + "Receive data."); int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); SocketLogMgt.SetLog(this, _socketID + "Receive succeeded. " + bytes.ToString() + " bytes."); string str = encoder.GetString(bytesReceived, 0, bytes); sb.Append(str); strReceived = sb.ToString(); rec = !SocketHelper.FindBlockEnding(strReceived); } _allDone.WaitOne(); // need not to set timeout here, we can depend on socket timeout of the Receive() method. if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, strReceived); SocketLogMgt.SetLog(this, "------------------------"); } strReceived = SocketHelper.UnpackMessageBlock(strReceived); return(new SocketResult(SocketResultType.Success, strReceived)); // send and receive success } catch (SocketException se) { SocketLogMgt.SetLastError(this, se); SocketResult ret = new SocketResult(se); ret.Type = SocketResultType.Unknown; return(ret); // meet exception during sending or receiving // (for example, it may be caused by the connection has expired [controled by the lower levels] // after some period of time without sending or receving), // and we need to recreate a new connection and try again, // please see SendData() for details. } catch (Exception err) { SocketLogMgt.SetLastError(this, err); return(new SocketResult(err)); } finally { SocketLogMgt.SetLog(this, ": Send Data End"); SocketLogMgt.SetLog(this, "=============================================\r\n"); } }
public static SocketResult SendData(SocketClientConfig config, string content) { SocketResult result = SocketResult.Empty; try { SocketLogMgt.SetLog("============================================="); SocketLogMgt.SetLog(": Send Data Begin."); SocketLogMgt.SetLog(config); string strSend = SocketHelper.PackMessageBlock(content); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(": Data to be sent."); SocketLogMgt.SetLog("------------------------"); SocketLogMgt.SetLog(strSend); SocketLogMgt.SetLog("------------------------"); } Byte[] bytesSent = null; System.Text.Encoding encoder = SocketHelper.GetEncoder(config); if (encoder != null) { bytesSent = encoder.GetBytes(strSend); } if (bytesSent == null) { SocketLogMgt.SetLog(SocketLogType.Error, "Encode data failed."); return(SocketResult.SendFailed); } Byte[] bytesReceived = new Byte[config.ReceiveResponseBufferSizeKB * 1024]; SocketLogMgt.SetLog(": Socket prepared."); SocketLogMgt.SetLog("------------------------"); string strReceived = null; StringBuilder sb = new StringBuilder(); IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(config.IPAddress), config.Port); using (Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { int id = SocketHelper.GetNewSocketID(); string strID = "(" + id.ToString() + ") "; //socket.NoDelay = true; socket.SendTimeout = config.SendTimeout; socket.ReceiveTimeout = config.ReceiveTimeout; SocketLogMgt.SetLog(strID + "Socket created."); socket.Connect(ipe); if (socket.Connected) { SocketLogMgt.SetLog(strID + "Socket connected."); } else { SocketLogMgt.SetLog(SocketLogType.Warning, strID + "Connection failed."); return(SocketResult.Disconnect); } _allDone.Reset(); #region session 1 SocketLogMgt.SetLog(strID + "Send data."); socket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(OnDataSent), new SocketWrapper(strID, socket)); bool rec = true; while (rec) { if (!socket.Connected) { SocketLogMgt.SetLog(SocketLogType.Warning, strID + "Connection closed."); break; } SocketLogMgt.SetLog(strID + "Receive data."); int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); SocketLogMgt.SetLog(strID + "Receive succeeded. " + bytes.ToString() + " bytes."); string str = encoder.GetString(bytesReceived, 0, bytes); sb.Append(str); strReceived = sb.ToString(); rec = !SocketHelper.FindBlockEnding(strReceived); } #endregion #region session 2 //SocketLogMgt.SetLog(strID + "Send data."); //socket.BeginSend(bytesSent, 0, bytesSent.Length, 0, // new AsyncCallback(OnDataSent), new SocketWrapper(strID, socket)); //rec = true; //while (rec) //{ // if (!socket.Connected) // { // SocketLogMgt.SetLog(SocketLogType.Warning, strID + "Connection closed."); // break; // } // SocketLogMgt.SetLog(strID + "Receive data."); // int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0); // SocketLogMgt.SetLog(strID + "Receive succeeded. " + bytes.ToString() + " bytes."); // string str = encoder.GetString(bytesReceived, 0, bytes); // sb.Append(str); // strReceived = sb.ToString(); // rec = !SocketHelper.FindBlockEnding(strReceived); //} #endregion _allDone.WaitOne(); // need not to set timeout here, we can depend on socket timeout of the Receive() method. socket.Shutdown(SocketShutdown.Both); socket.Close(); SocketLogMgt.SetLog(strID + "Socket disconnected."); } SocketLogMgt.SetLog("------------------------"); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(": Data received."); SocketLogMgt.SetLog("------------------------"); SocketLogMgt.SetLog(strReceived); SocketLogMgt.SetLog("------------------------"); } strReceived = SocketHelper.UnpackMessageBlock(strReceived); result = new SocketResult(SocketResultType.Success, strReceived); } catch (Exception err) { SocketLogMgt.SetLastError(err); result = new SocketResult(err); } SocketLogMgt.SetLog(": Send Data End"); SocketLogMgt.SetLog("=============================================\r\n"); return(result); }