public Listener(IPEndPoint ipep) { m_Accepted = new Queue<Socket>(); m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot; m_Listener = Bind(ipep); if (m_Listener == null) { return; } DisplayListener(); #if NewAsyncSockets m_EventArgs = new SocketAsyncEventArgs(); m_EventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( Accept_Completion ); Accept_Start(); #else m_OnAccept = OnAccept; try { IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener); } catch (SocketException ex) { NetState.TraceException(ex); } catch (ObjectDisposedException) { } #endif }
/// <summary> /// A connection to our server, always listening asynchronously. /// </summary> /// <param name="socket">The Socket for the connection.</param> /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param> /// <param name="dataReceived">A callback invoked when data is recieved.</param> /// <param name="disconnectedCallback">A callback invoked on disconnection.</param> public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived, DisconnectedCallback disconnectedCallback) { logger = new ElibLogging("data"); this.AuthorizationType = Securtiy.AuthorizationType.Anonymous; lock (this) { var remotIP = socket.RemoteEndPoint as IPEndPoint; var localIP = socket.LocalEndPoint as IPEndPoint; State state = new State() { socket = socket, dataReceived = dataReceived, disconnectedCallback = disconnectedCallback, Device = new Device() { RemoteIP = remotIP.Address.ToString(), LocalIP = localIP.Address.ToString() } }; eventArgs = args; eventArgs.Completed += ReceivedCompleted; eventArgs.UserToken = state; ListenForData(eventArgs); } }
private void Accept_Completed(object sender, SocketAsyncEventArgs e) { Socket ClientSocket = e.AcceptSocket; Console.WriteLine("Accepting connection"); byte[] bytesFrom = new byte[LENGTH.MAX_PACKET_LEN]; string dataFromClient = null; ClientSocket.Receive(bytesFrom); dataFromClient = System.Text.Encoding.UTF8.GetString(bytesFrom); ChatProtocol chatProtocol = JsonConvert.DeserializeObject<ChatProtocol>(dataFromClient); socketToClient.Add(ClientSocket, chatProtocol.sender_id); clientToSocket.Add(chatProtocol.sender_id, ClientSocket); Console.WriteLine(chatProtocol.sender_id + " Joined "); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); szData = new byte[1024]; args.SetBuffer(szData, 0, 1024); args.Completed += new EventHandler<SocketAsyncEventArgs>(Receive_Completed); ClientSocket.ReceiveAsync(args); e.AcceptSocket = null; m_ServerSocket.AcceptAsync(e); }
public int HandlePrefix(SocketAsyncEventArgs saea, DataToken dataToken, int remainingBytesToProcess) { if (remainingBytesToProcess >= 4 - dataToken.prefixBytesDone) { for (int i = 0; i < 4 - dataToken.prefixBytesDone; i++) { dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i]; } remainingBytesToProcess = remainingBytesToProcess - 4 + dataToken.prefixBytesDone; dataToken.bufferSkip += 4 - dataToken.prefixBytesDone; dataToken.prefixBytesDone = 4; dataToken.messageLength = BitConverter.ToInt32(dataToken.byteArrayForPrefix, 0); } else { for (int i = 0; i < remainingBytesToProcess; i++) { dataToken.byteArrayForPrefix[dataToken.prefixBytesDone + i] = saea.Buffer[dataToken.DataOffset + i]; } dataToken.prefixBytesDone += remainingBytesToProcess; remainingBytesToProcess = 0; } return remainingBytesToProcess; }
public override bool OnEvent(SocketAsyncEventArgs e) { if (Protocol.IsEnqueueForDelete || Protocol.TimePeriodElapsed()) return true; Logger.FATAL("Unable to handle TimeElapsed event"); IOHandlerManager.EnqueueForDelete(this); return false; }
private void OnSeaeReceive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { try { if (e.SocketError == System.Net.Sockets.SocketError.Success && e.BytesTransferred > 0) { ChannelReceiveData(e); } } catch (System.Net.Sockets.SocketException se) { OnChannelError(this, new ErrorEventArgs { Error = se, Tag = "Server Udp Receive" }); Dispose(); } catch (Exception e_) { OnChannelError(this, new ErrorEventArgs { Error = e_, Tag = "Server Udp Receive" }); } finally { Push(e); } OnUdpReceive(null); }
internal async Task InitializeAsync() { await Task.Run(() => { var args = new SocketAsyncEventArgs { UserToken = _socket, RemoteEndPoint = _endPoint }; args.Completed += async (sender, eventArgs) => { if (((Socket)sender).Connected) { _isConnected = true; await _display.WriteAsync("NTRIP Connected"); await Task.Delay(500); } else { _isConnected = false; await _display.WriteAsync("NTRIP Connection failed"); } }; _socket.ConnectAsync(args); }).ConfigureAwait(false); }
/// <summary> /// Listens for socket connection on a given address and port. /// </summary> /// <param name="endPoint">The endpoint to listen on.</param> /// <param name="connectionBacklog">The connection backlog.</param> public TcpSocketListener(IPEndPoint endPoint, Int32 connectionBacklog) { this.endPoint = endPoint; args = new SocketAsyncEventArgs(); args.Completed += SocketAccepted; }
private SocketAsyncEventArgs CreateConnectSocketArgs() { var socketArgs = new SocketAsyncEventArgs(); socketArgs.Completed += ConnectCompleted; socketArgs.UserToken = new CallbacksStateToken(); return socketArgs; }
internal static bool HandleMessage(SocketAsyncEventArgs e, DataHoldingUserToken token, int remainingBytesToProcess) { bool msgIsReady = false; if (token.countReccMsgDone == 0) { token.byteArrayRecvMsg = new byte[token.lenRecvMsg]; } if (remainingBytesToProcess + token.countReccMsgDone == token.lenRecvMsg) { Buffer.BlockCopy(e.Buffer, token.receiveMessageOffset, token.byteArrayRecvMsg, token.countReccMsgDone, remainingBytesToProcess); msgIsReady = true; } else { Buffer.BlockCopy(e.Buffer, token.receiveMessageOffset, token.byteArrayRecvMsg, token.countReccMsgDone, remainingBytesToProcess); token.receiveMessageOffset -= token.countRecvPfxDoneThisOp; token.countReccMsgDone += remainingBytesToProcess; } return msgIsReady; }
protected override bool ListenAsync(SocketAsyncEventArgs saea) { var bufferSize = ("Hi Peer2Net node here:" + Guid.Empty + ":127.0.0.1:0000").Length; saea.SetBuffer(new byte[bufferSize], 0, bufferSize); saea.RemoteEndPoint = new IPEndPoint(IPAddress.Any, Port); return Listener.ReceiveFromAsync(saea); }
/// <summary> /// Initializes a new instance of the <see cref="UdpSocketWrapper"/> class. /// </summary> public UdpSocketWrapper() { // operation arguments var args = new SocketAsyncEventArgs(); args.Completed += SocketAsyncEventArgs_Completed; _socketOperation = args; }
public SocketAsyncEventArgsProxy(SocketAsyncEventArgs socketEventArgs, bool isRecyclable) { SocketEventArgs = socketEventArgs; OrigOffset = socketEventArgs.Offset; SocketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArgs_Completed); IsRecyclable = isRecyclable; }
/// <summary> /// 启动监听 /// </summary> /// <param name="config">服务器配置</param> /// <returns></returns> public override bool Start(IServerConfig config) { m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { //关联终结地 m_ListenSocket.Bind(this.Info.EndPoint); //设置监听最大连接数 m_ListenSocket.Listen(m_ListenBackLog); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); //初始化套接字操作 SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs(); m_AcceptSAE = acceptEventArg; //定义一个连接完成事件 acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed); if (!m_ListenSocket.AcceptAsync(acceptEventArg)) { ProcessAccept(acceptEventArg); } return true; } catch (Exception e) { OnError(e); return false; } }
public void Connect(IPEndPoint address) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = address; args.Completed += new EventHandler<SocketAsyncEventArgs>(socket_Connected); socket.ConnectAsync(args); }
public ArraySegment<byte> CopyToNextSegment(SocketAsyncEventArgs sourceEventArgs) { Byte[] array; int offset; int count = sourceEventArgs.BytesTransferred; Locate(count, out array, out offset); var data = new ArraySegment<byte>(array, offset, count); if (sourceEventArgs.Buffer != null) { Buffer.BlockCopy(sourceEventArgs.Buffer, sourceEventArgs.Offset, array, offset, count); } else if (sourceEventArgs.BufferList != null) { int currentOffset = offset; int copiedCount = 0; foreach (var item in sourceEventArgs.BufferList) { int willcopyCount = count - copiedCount; int copyingCount = willcopyCount > item.Count ? item.Count : willcopyCount; Buffer.BlockCopy(item.Array, item.Offset, array, currentOffset, copyingCount); copiedCount = copiedCount + copiedCount; currentOffset = copiedCount + offset; } } return data; }
/// <summary> /// Starts to listen /// </summary> /// <param name="config">The server config.</param> /// <returns></returns> public override bool Start(IServerConfig config) { m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { m_ListenSocket.Bind(this.Info.EndPoint); m_ListenSocket.Listen(m_ListenBackLog); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); // m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed); if (!m_ListenSocket.AcceptAsync(acceptEventArg)) ProcessAccept(acceptEventArg); return true; } catch (Exception e) { OnError(e); return false; } }
// Initializes the server by preallocating reusable buffers and // context objects. These objects do not need to be preallocated // or reused, but it is done this way to illustrate how the API can // easily be used to create reusable objects to increase server performance. // public void Init() { // Allocates one large byte buffer which all I/O operations use a piece of. This gaurds // against memory fragmentation m_bufferManager.InitBuffer(); // preallocate pool of SocketAsyncEventArgs objects SocketAsyncEventArgs readWriteEventArg; for (int i = 0; i < m_numConnections; i++) { //Pre-allocate a set of reusable SocketAsyncEventArgs readWriteEventArg = new SocketAsyncEventArgs(); readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); readWriteEventArg.UserToken = new AsyncUserToken(); //((AsyncUserToken) readWriteEventArg.UserToken).name = "e" + i; // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object m_bufferManager.SetBuffer(readWriteEventArg); // add SocketAsyncEventArg to the pool m_readWritePool.Push(readWriteEventArg); } }
SocketAsyncEventArgs AllocNewAsyncArgs() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += m_receiveCompleteHandler; return args; }
private void Client_SizeReceived(object sender, SocketAsyncEventArgs e) { e.Completed -= Client_SizeReceived; EnsureSocketSuccess(e, () => { SocketAsyncEventArgsUserToken userToken = (SocketAsyncEventArgsUserToken)e.UserToken; int sizeToReceive = BitConverter.ToInt32(e.Buffer.Take(4).ToArray(), 0); uint?messageID = (e.Buffer.Length == 8) ? (uint?)BitConverter.ToUInt32(e.Buffer.Skip(4).Take(4).ToArray(), 0) : null; const int sizeLimitForLogging = 10 * 1024 * 1024; // 10 MB if (sizeToReceive >= sizeLimitForLogging) { CoreLogger.UniqueInstance.Warn(string.Format("SizeToReceive is larger than 10 MB. Size is {0} bytes", sizeToReceive)); OnSocketError(System.Net.Sockets.SocketError.SocketError); return; } userToken.MessageID = messageID; userToken.SizeToReceive = sizeToReceive; userToken.CurrentRawMessageLength = 0; userToken.CurrentRawMessage = string.Empty; byte[] messageBuffer = new byte[userToken.SizeToReceive]; e.SetBuffer(messageBuffer, 0, messageBuffer.Length); e.Completed += Client_MessageReceived; userToken.Socket.InvokeAsyncMethod(userToken.Socket.ReceiveAsync, Client_MessageReceived, e); }); }
public Mediator(SocketAsyncEventArgs e) { this.saeaObject = e; this.theIncomingDataPreparer = new IncomingDataPreparer(saeaObject); this.theOutgoingDataPreparer = new OutgoingDataPreparer(); }
void ConnectCompleted( object sender, SocketAsyncEventArgs e ) { sock = sender as Socket; if ( sock == null ) { OnDisconnected( EventArgs.Empty ); return; } if ( e.SocketError != SocketError.Success ) { DebugLog.WriteLine( "TcpConnection", "Unable to connect: {0}", e.SocketError ); OnDisconnected( EventArgs.Empty ); return; } DebugLog.WriteLine( "TcpConnection", "Connected!" ); isConnected = true; netStream = new NetworkStream( sock, false ); netReader = new BinaryReader( netStream ); netWriter = new BinaryWriter( netStream ); // initialize our network thread netThread = new Thread( NetLoop ); netThread.Name = "TcpConnection Thread"; netThread.Start(); OnConnected( EventArgs.Empty ); }
private void ProcessRequest(ClientObject co) { Client.Request Req = new Client.Request() { Header = co.Header, Body = co.Buffer.Count > 0?co.Buffer.ToArray():null, Client = co.EventArgs.AcceptSocket }; Response Res = HandleRequest(Req); Res.Header.ContentLength = Res.Body != null ? Res.Body.Length : 0; Res.Header["Connection"] = KeepAlive ? "KeepAlive" : "Close"; List <byte> buf = new List <byte>(); buf.AddRange(Encoding.UTF8.GetBytes(Res.Header.ToHttpHeader())); buf.AddRange(Base.NewLineBytes); if (Res.Body != null && Res.Body.Length > 0) { buf.AddRange(Res.Body); } byte[] bts = buf.ToArray(); System.Net.Sockets.SocketAsyncEventArgs saea = new System.Net.Sockets.SocketAsyncEventArgs(); saea.Completed += SocketAsyncEventArgs_SendCompleted; saea.SetBuffer(bts, 0, bts.Length); saea.AcceptSocket = co.EventArgs.AcceptSocket; saea.UserToken = co.EventArgs.UserToken; co.EventArgs.AcceptSocket.SendAsync(saea); Debug.WriteLine(Req.Header.Method + " " + Req.Header.Path + " " + Res.Header.Code + " " + Res.Header.Status); }
private void ProcessSAEA(object sender, SAEA saea) { switch (saea.LastOperation) { case SocketAsyncOperation.Send: ProcessSendAsync(saea); break; case SocketAsyncOperation.SendTo: ProcessSendToAsync(saea); break; case SocketAsyncOperation.Receive: ProcessReceiveAsync(saea); break; case SocketAsyncOperation.ReceiveFrom: ProcessReceiveFromAsync(saea); break; default: if (!OnSAEACompletedCallback(sender, saea)) { NetDebug.Log("{0} ProcessSAEA, not process!", LOG_PREFIX); } break; } }
private void Accept_Completed(object sender, SocketAsyncEventArgs e) { e.Completed -= Accept_Completed; if (e.SocketError != SocketError.Success) { var error = string.Format("There was an error accepting a socket connection ({0}).", Enum.GetName(typeof(SocketError), e.SocketError)); OnConnectionAccepted(new ConnectionAcceptedEventArgs(error)); return; } var clientConnection = new ClientConnection(e.AcceptSocket); try { OnConnectionAccepted(new ConnectionAcceptedEventArgs(clientConnection)); clientConnection.ShutdownAndClose(); } finally { ((IDisposable)clientConnection).Dispose(); } OnConnectionClosed(); AcceptIncomingConnection(); }
/// <summary> /// <see cref="AbstractTcpClient.ConnectInternal"/> /// </summary> protected override void ConnectInternal(Socket socket, EndPoint endpoint) { try { if (Object.ReferenceEquals(socket, null)) { socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } if (Object.ReferenceEquals(connectEventArgs, null)) { connectEventArgs = new SocketAsyncEventArgs(); connectEventArgs.Completed += OnConnectCompleted; } connectEventArgs.RemoteEndPoint = endpoint; connectEventArgs.UserToken = socket; bool pending = socket.ConnectAsync(connectEventArgs); if (!pending) { OnConnect(connectEventArgs); } } catch (Exception e) { Log.Error("{0} error connecting to {1} : {2}", Name, endpoint, e.Message); OnConnectError(socket, endpoint); } }
protected override void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { if (callBack != null) { callBack(e); } }
/// <summary> /// Initializes a new instance of the <see cref="TcpChannel" /> class. /// </summary> /// <param name="readBuffer">Buffer used for our reading.</param> /// <param name="encoder">Used to encode messages before they are put in the MicroMessage body of outbound messages.</param> /// <param name="decoder"> /// Used to decode the body of incoming MicroMessages. The <c>MessageReceived</c> delegate will be /// overridden by this class. /// </param> public TcpChannel(IBufferSlice readBuffer, IMessageEncoder encoder, IMessageDecoder decoder) { if (readBuffer == null) throw new ArgumentNullException("readBuffer"); if (encoder == null) throw new ArgumentNullException("encoder"); if (decoder == null) throw new ArgumentNullException("decoder"); _readArgs = new SocketAsyncEventArgs(); _readArgs.SetBuffer(readBuffer.Buffer, readBuffer.Offset, readBuffer.Capacity); _readArgs.Completed += OnReadCompleted; _readArgsWrapper = new SocketAsyncEventArgsWrapper(_readArgs); _encoder = encoder; _decoder = decoder; _decoder.MessageReceived = OnMessageReceived; _writeArgs = new SocketAsyncEventArgs(); _writeArgs.Completed += OnSendCompleted; _writeArgsWrapper = new SocketAsyncEventArgsWrapper(_writeArgs); _sendCompleteAction = (channel, message) => { }; _disconnectAction = (channel, exception) => { }; ChannelFailure = (channel, error) => HandleDisconnect(SocketError.ProtocolNotSupported); RemoteEndpoint = EmptyEndpoint.Instance; ChannelId = GuidFactory.Create().ToString(); Data = new ChannelData(); }
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA // when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint) { lock (lockObject) { GlobalLog.Assert(endPoint.AddressFamily == AddressFamily.Unspecified || endPoint.AddressFamily == AddressFamily.InterNetwork || endPoint.AddressFamily == AddressFamily.InterNetworkV6, "MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString()); this.userArgs = args; this.endPoint = endPoint; // If Cancel() was called before we got the lock, it only set the state to Canceled: we need to // fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail. if (state == State.Canceled) { SyncFail(new SocketException(SocketError.OperationAborted)); return false; } GlobalLog.Assert(state == State.NotStarted, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state"); state = State.DnsQuery; IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null); if (result.CompletedSynchronously) { return DoDnsCallback(result, true); } else { return true; } } }
public OSClient(IEFMagLinkRepository repository) { // First we set up our mutex and semaphore mutex = new Mutex(); connected = false; _repository = repository; item = new SocketAsyncEventArgs(); _timerClient.Elapsed += new System.Timers.ElapsedEventHandler(_timerClient_Elapsed); _timerClient.Interval = 10000; _timerClient.Start(); _timerClientConnecTimer.Elapsed += new System.Timers.ElapsedEventHandler(_timerClientConnecTimer_Elapsed); _timerClientConnecTimer.Interval = 15000; _timerClientConnecTimer.Start(); numconnections = 0; item.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); item.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize)); socketpool = new OSAsyncEventStack(Convert.ToInt32(Settings._instance.NumConnect)); for (Int32 i = 0; i < Convert.ToInt32(Settings._instance.NumConnect); i++) { SocketAsyncEventArgs item1 = new SocketAsyncEventArgs(); item1.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); item1.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize)); socketpool.Push(item1); } }
public void SendPacket(byte[] buffer, int offset, int size, Action<StreamBuffer> onSent = null) { try { lock (_session) { if (_session.Socket == null) return; SocketAsyncEventArgs saea = new SocketAsyncEventArgs(); saea.Completed += SendComplete; saea.SetBuffer(buffer, offset, size); if (onSent != null) saea.UserToken = new NetworkSendToken(new StreamBuffer(buffer, offset, size), onSent); if (_session.Socket.SendAsync(saea) == false) ReceiveComplete(null, saea); } } catch (SocketException) { } catch (Exception e) { Logger.Err(LogMask.Aegis, e.ToString()); } }
public void OnConnection(object sender, SocketAsyncEventArgs e) { if (e.BytesTransferred > 0) { var packetData = new byte[e.BytesTransferred]; Buffer.BlockCopy(dataBuffer, 0, packetData, 0, e.BytesTransferred); ProcessPacket(new Packet(packetData)); } PacketLog.Write<Packet>(dataBuffer, e.BytesTransferred, client.RemoteEndPoint as IPEndPoint); e.Completed -= OnConnection; e.Completed += Process; var sHello = new Packet(ServerMessage.SHello); sHello.Write(9165, 32); // BuildNumber sHello.Write(1, 32); // RealmId sHello.Write(0, 32); // RealmGroupId sHello.Write(0, 32); sHello.Write(0, 64); sHello.Write(0, 16); sHello.Write(11, 5); // ConnectionType sHello.Write(0xBDD06089, 32); // NetworkMessageCRC sHello.Write(0, 32); sHello.Write(0, 64); sHello.Write(0, 32); Send(sHello); client.ReceiveAsync(e); }
public void ConnectTo(string ip, int port) { State = ConnectionState.NotConnected; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress[] ips = Dns.GetHostAddresses(ip); var addr = ips[0]; var hostEndPoint = new IPEndPoint(addr, port); var connectEA = new SocketAsyncEventArgs(); connectEA.RemoteEndPoint = hostEndPoint; connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{ switch (e.LastOperation) { case SocketAsyncOperation.Connect: UnityEngine.Debug.Log("Connect success"); break; default: throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } connectEA.Dispose(); State = ConnectionState.Connected; }; State = ConnectionState.Connecting; socket.ConnectAsync(connectEA); }
public SocketAsyncEventArgsDecorator(SocketAsyncEventArgs socketAsyncEventArgs) { if (socketAsyncEventArgs == null) throw new ArgumentNullException("socketAsyncEventArgs"); this.socketAsyncEventArgs = socketAsyncEventArgs; }
public void BufferPool_CheckIn_Resets_SocketArg_Data_Buffer() { var socketArg = new SocketAsyncEventArgs(); BufferPool.Instance.CheckOut(socketArg); BufferPool.Instance.CheckIn(socketArg); Assert.IsNull(socketArg.Buffer); }
internal static void Receive_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { BufferBlock block = e.UserToken as BufferBlock; if (block == null) { return; } Network <T> network = block.UserToken as Network <T>; e.UserToken = null; if (network?.HandleReceived(e) == true) { if (!network.isDisconnected) { BufferBlock newBlock = BufferManager.Instance.RequestBufferBlock(); newBlock.UserToken = network; e.UserToken = newBlock; e.SetBuffer(newBlock.Buffer, newBlock.StartIndex, newBlock.MaxLength); try { if (!network.sock.ReceiveAsync(e)) { Receive_Completed(null, e); } } catch (Exception ex) { Logger.Log.Error(ex); newBlock.Free(); } } } else { if (network != null) { if (network.autoLock) { ClientManager.EnterCriticalArea(); } network.Disconnect(); if (network.autoLock) { ClientManager.LeaveCriticalArea(); } } else { Logger.Log.Warn("network == null"); } } block.Free(); }
private bool HandleReceived(System.Net.Sockets.SocketAsyncEventArgs e) { if (isDisconnected || client == null) { return(false); } if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { try { DateTime now = DateTime.Now; this.receivedBytes += e.BytesTransferred; if ((now - this.receiveStamp).TotalSeconds > 10) { this.avarageReceive = (int)(this.receivedBytes / (now - this.receiveStamp).TotalSeconds); this.receivedBytes = 0; this.receiveStamp = now; } if (this.lastContent == null) { byte[] buf = new byte[e.BytesTransferred]; Array.Copy(e.Buffer, e.Offset, buf, 0, e.BytesTransferred); if (!this.isDisconnected) { this.OnReceivePacket(buf); } } else { byte[] buf = new byte[e.BytesTransferred + this.lastContent.Length]; this.lastContent.CopyTo(buf, 0); Array.Copy(e.Buffer, e.Offset, buf, this.lastContent.Length, e.BytesTransferred); if (!this.isDisconnected) { this.OnReceivePacket(buf); } } } catch (Exception ex) { Logger.Log.Error(ex); } } else { if (e.SocketError != SocketError.Success && e.SocketError != SocketError.ConnectionReset && e.SocketError != SocketError.ConnectionAborted) { Logger.Log.Error(new SocketException((int)e.SocketError)); } return(false); } return(true); }
private void TMNRPCClient_SocketError(object sender, SocketErrorEventArgs e) { SocketAsyncEventArgs.Dispose(); SocketAsyncEventArgs = null; if (e.SocketError == System.Net.Sockets.SocketError.ConnectionReset && ServerClosedConnection != null) { ServerClosedConnection(this, EventArgs.Empty); } }
private void Client_MessageReceived(object sender, SocketAsyncEventArgs e) { e.Completed -= Client_MessageReceived; EnsureSocketSuccess(e, () => { SocketAsyncEventArgsUserToken userToken = (SocketAsyncEventArgsUserToken)e.UserToken; userToken.CurrentRawMessageLength += e.BytesTransferred; userToken.CurrentRawMessage += Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred); if (userToken.MoreBytesNeedToBeRead) { byte[] messageBuffer = new byte[userToken.RemainingBytesToReceive]; e.SetBuffer(messageBuffer, 0, messageBuffer.Length); e.Completed += Client_MessageReceived; userToken.Socket.InvokeAsyncMethod(userToken.Socket.ReceiveAsync, Client_MessageReceived, e); return; } if (userToken.MessageID.HasValue) { if ((userToken.MessageID & CALLBACK_IDENTIFIER) == 0) { // message is a callback XElement messageElement = TryParseXElement(userToken.CurrentRawMessage); if (messageElement != null && !Callbacks.CheckForKnownMethodCallback(messageElement)) { CoreLogger.UniqueInstance.Error("Found unknown callback: " + userToken.CurrentRawMessage); } } else { // message is a method reply lock (_methodResponsesLockObject) { MethodResponses[userToken.MessageID.Value] = userToken.CurrentRawMessage; } } } else if (string.Compare(userToken.CurrentRawMessage, "GBXRemote 2", StringComparison.OrdinalIgnoreCase) != 0) { OnSocketError(System.Net.Sockets.SocketError.ProtocolNotSupported); return; } else { ThreadPool.QueueUserWorkItem(x => OnReadyForSendingCommands()); } ReadMessageWithPrefix(e, true); }); }
private void IOCompleted(object Sender, Sockets.SocketAsyncEventArgs EventStatement) { switch (EventStatement.LastOperation) { case Sockets.SocketAsyncOperation.Receive: StateObject ClientSource = EventStatement.UserToken as StateObject; ReadClientInput(ClientSource); break; default: break; } }
void SocketAsyncEventArgs_SendCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { String key = e.UserToken as String; if (e.LastOperation == SocketAsyncOperation.Send) { // Send Completed if (!KeepAlive) { e.AcceptSocket.Close(); } } }
private void IO_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { SocketAsyncEventArgsX ex = (SocketAsyncEventArgsX)e; if (ex.IsReceive) { ReceiveCompleted(e); } else { SendCompleted(e); } }
private void ReadMessageWithPrefix(SocketAsyncEventArgs e, bool includeMessageID) { EnsureSocketSuccess(e, () => { SocketAsyncEventArgsUserToken userToken = (SocketAsyncEventArgsUserToken)e.UserToken; byte[] sizeBuffer = new byte[includeMessageID ? 8 : 4]; e.SetBuffer(sizeBuffer, 0, sizeBuffer.Length); e.Completed += Client_SizeReceived; userToken.Socket.InvokeAsyncMethod(userToken.Socket.ReceiveAsync, Client_SizeReceived, e); }); }
internal static void Send_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { BufferBlock block = e.UserToken as BufferBlock; Network <T> network = block.UserToken as Network <T>; block.Free(); if (network == null || network.isDisconnected || network.client == null) { ClientManager <T> .FinishSendQuest(e); return; } lock (network.bufferLockObj) { if (network.pendingQueue.Count > 0) { BufferBlock block2 = network.pendingQueue.Dequeue(); ClientManager <T> .EnqueueSendRequest(network, block2); } else { network.aldreadyInQueue = false; } } try { if (e.SocketError != SocketError.Success) { if (e.SocketError != SocketError.ConnectionReset && e.SocketError != SocketError.ConnectionAborted) { Logger.Log.Error(new SocketException((int)e.SocketError)); } if (network.autoLock) { ClientManager.EnterCriticalArea(); } network.Disconnect(); if (network.autoLock) { ClientManager.LeaveCriticalArea(); } } } catch (Exception ex) { Logger.Log.Error(ex); } ClientManager <T> .FinishSendQuest(e); }
private void EnsureSocketSuccess(SocketAsyncEventArgs socketEventArgs, Action action) { switch (socketEventArgs.SocketError) { case System.Net.Sockets.SocketError.Success: action(); break; // more handling here later default: OnSocketError(socketEventArgs.SocketError); break; } }
private void Client_Connected(object sender, SocketAsyncEventArgs e) { e.Completed -= Client_Connected; EnsureSocketSuccess(e, () => { if (Connected != null) { Connected(this, EventArgs.Empty); } ReadMessageWithPrefix(e, false); }); }
private void iSend_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { if (CancelSocket) { return; } try { if (e.SocketError != SocketError.Success) { NNTPError zErr = Common.TranslateError(e.SocketError); Close(zErr.Code, zErr.Message); return; } } catch (Exception ex) { Close(971, "Send: " + ex.Message); } }
private void iReceive_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { if (CancelSocket) { return; } try { if (e.SocketError != SocketError.Success) { NNTPError zErr = Common.TranslateError(e.SocketError); Close(zErr.Code, zErr.Message); return; } if (e.BytesTransferred < 1) { Close(954, "Socket closed."); return; } if (DataStream == null) { DataStream = new MemoryStream(e.BytesTransferred + 1); } DataStream.Position = DataStream.Length; DataStream.Write(e.Buffer, e.Offset, e.BytesTransferred); if (e.BytesTransferred >= (e.Buffer.Length / 2.0)) // Dynamic resize { if ((e.Buffer.Length - 1) < (MaxBufferSize - 5)) { int bsize = 0; if ((e.Buffer.Length * 2) < MaxBufferSize) { bsize = e.Buffer.Length * 2 + 1; } else { bsize = MaxBufferSize + 1; } SetBuffer(bsize); } } SafeFire(Received, new WorkArgs(DataStream)); } catch (Exception ex) { Close(960, "Rcv: " + ex.Message); } }
private void OnReceiveCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(e.Buffer, 0, e.BytesTransferred); BrodcastMessage msg = stream.Deserialize <BrodcastMessage>(e.BytesTransferred); if (msg.MessageType == "SMART_ROUTE") { if (!msg.Token.VerifyMd5Hash(msg.NodeID + mTokenKey)) { return; } if (msg.NodeID != NodeID && msg.Cluster == this.Cluster) { Loger.Process(LogType.BROAD_DEBUG, "broadcast reveive {0}", msg); if (string.IsNullOrEmpty(msg.IP)) { msg.IP = ((IPEndPoint)e.RemoteEndPoint).Address.ToString(); } try { if (!mDiscoverTable.ContainsKey(msg.NodeID)) { DiscoverEventArgs de = new DiscoverEventArgs(); de.Address = msg.IP; de.Port = int.Parse(msg.Port); de.NodeID = msg.NodeID; mDiscoverTable[msg.NodeID] = de; OnDiscorver(de); } } catch (Exception e__) { Loger.Process(LogType.BROAD_ERROR, "node ping error {0}", e__.Message); } } } } catch (Exception e_) { Loger.Process(LogType.BROAD_ERROR, "broadcast reveive error {0}", e_.Message); } finally { OnReceive(); } }
void SocketAsyncEventArgs_AcceptCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { if (e != null) { if (e.AcceptSocket != null && e.AcceptSocket.RemoteEndPoint != null && e.LastOperation == SocketAsyncOperation.Accept) { Debug.WriteLine(e.AcceptSocket.RemoteEndPoint.ToString()); System.Net.Sockets.SocketAsyncEventArgs saea = new System.Net.Sockets.SocketAsyncEventArgs(); saea.Completed += SocketAsyncEventArgs_ReceiveCompleted; saea.AcceptSocket = e.AcceptSocket; saea.UserToken = e.AcceptSocket.RemoteEndPoint.ToString(); saea.SetBuffer(new byte[BufferSize], 0, BufferSize); e.AcceptSocket.ReceiveAsync(saea); } else { Debug.WriteLine("Stop"); } } bool Crashed = false; try { Crashed = ServerSocket == null || ServerSocket.LocalEndPoint == null; } catch { } if (Crashed && _Status == ServerStatus.Running) { Clients.Clear(); ServerSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); ServerSocket.Bind(new IPEndPoint(IPAddress.Parse(Address), Port)); ServerSocket.Listen(BackLog); Debug.WriteLine(String.Format("Listen at {0}:{1}", Address, Port)); // SocketAsyncEventArgs_AcceptCompleted(null, null); } else if (ServerSocket != null) { System.Net.Sockets.SocketAsyncEventArgs saea = new System.Net.Sockets.SocketAsyncEventArgs(); saea.Completed += SocketAsyncEventArgs_AcceptCompleted; ServerSocket.AcceptAsync(saea); } }
public void Connect(string host, int?port) { if (SocketAsyncEventArgs != null) { return; } MethodResponses.Clear(); if (port == null) { port = DEFAULT_PORT; } if (host == null || host.Trim().Length == 0) { host = "localhost"; } SocketAsyncEventArgs = new SocketAsyncEventArgs(); IPAddress remoteIP; if (!IPAddress.TryParse(host, out remoteIP)) { IPHostEntry hostEntry = Dns.GetHostEntry(host); if (hostEntry.AddressList.Length == 0) { throw new InvalidOperationException(string.Format("Could not resolve host: {0}", host)); } remoteIP = hostEntry.AddressList[0]; } IPEndPoint remoteEndPoint = new IPEndPoint(remoteIP, port.Value); Socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs.RemoteEndPoint = remoteEndPoint; SocketAsyncEventArgs.UserToken = new SocketAsyncEventArgsUserToken { Socket = Socket }; SocketAsyncEventArgs.Completed += Client_Connected; Socket.InvokeAsyncMethod(Socket.ConnectAsync, Client_Connected, SocketAsyncEventArgs); }
private void SendCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success && e.BytesTransferred > 0) { if (e.BytesTransferred < e.Count) { e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred); if (!mSocket.SendAsync(e)) { SendCompleted(this, e); } } } else { ReleaseSocket(); } }
private void ReceiveCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success && e.BytesTransferred > 0) { try { mPackage.Import(e.Buffer, 0, e.BytesTransferred); BeginReceive(); } catch (Exception e_) { ReleaseSocket(); OnError(e_); } } else { ReleaseSocket(); } }
void AcceptLoop(Sockets.SocketAsyncEventArgs EventStatement) { try { if (EventStatement == null) { EventStatement = new Sockets.SocketAsyncEventArgs(); EventStatement.Completed += AcceptEvent_Completed; } else { EventStatement.AcceptSocket = null; } bool EventTrigger = Socket.AcceptAsync(EventStatement);; if (!EventTrigger) { AcceptClientObject(EventStatement); } } catch (System.Exception) { } }
private void SendCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { this.sendEventArgsPool.Push(e); e.UserToken = null; if (e.SocketError == SocketError.Success && e.BytesTransferred > 0) { if (e.BytesTransferred < e.Count) { e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred); if (!this.clientSocket.SendAsync(e)) { SendCompleted(this, e); } } } else { IsConnected = false; this.RaiseEvent(this.Disconnected, new AsyncSocketTokenEventArgs(this.clientSocket)); } }
public bool Send(object message) { lock (this) { if (Connect()) { try { IMessage msg = mPackage.SendCast(message); byte[] data = mPackage.GetMessageData(msg); mSendSAEA = new SocketAsyncEventArgs(); mSendSAEA.Completed += SendCompleted; mSendSAEA.SetBuffer(data, 0, data.Length); if (!mSocket.SendAsync(mSendSAEA)) { SendCompleted(this, mSendSAEA); } return(true); } catch (SocketException se) { ReleaseSocket(); OnError(se); } catch (ObjectDisposedException ode) { ReleaseSocket(); OnError(ode); } catch (Exception e_) { OnError(e_); } } return(false); } }
private void AcceptClientObject(Sockets.SocketAsyncEventArgs EventStatement) { try { EventStatement.AcceptSocket.SetSocketOption(Sockets.SocketOptionLevel.Socket, Sockets.SocketOptionName.KeepAlive, true); StateObject ClientObject = new StateObject(EventStatement.AcceptSocket, this); ClientObject.ArgumentStack = new Sockets.SocketAsyncEventArgs(); ClientObject.ArgumentStack.Completed += IOCompleted; ClientObject.ArgumentStack.SetBuffer(ClientObject.DataReceived, 0, ClientObject.DataReceived.Length); ClientObject.ArgumentStack.AcceptSocket = EventStatement.AcceptSocket; ClientObject.ArgumentStack.SocketFlags = Sockets.SocketFlags.None; ClientObject.ArgumentStack.UserToken = ClientObject; lock (Clients) { Clients.Add(ClientObject); } bool EventTrigger = ClientObject.Sock.ReceiveAsync(ClientObject.ArgumentStack); AcceptLoop(EventStatement); if (!EventTrigger) { ReadClientInput(ClientObject); } } catch (System.Exception) { } }
private void iConnect_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { try { if (CancelSocket) { return; } if (e.SocketError != SocketError.Success) { NNTPError zErr = Common.TranslateError(e.SocketError); Close(zErr.Code, zErr.Message); return; } iReceive = new System.Net.Sockets.SocketAsyncEventArgs(); iReceive.Completed += new EventHandler<SocketAsyncEventArgs>(iReceive_Completed); if (MaxBufferSize < 1024) { MaxBufferSize = 1024; } ClearBuffer(); SafeFire(Connected, new WorkArgs(951, "Connected")); } catch (Exception ex) { Close(950, "Connect: " + ex.Message); } }
protected override void AsyncEventArgs_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { //if (e.BytesTransferred <= 0) //{ // Close(); // return; //} if (e.SocketError != SocketError.Success) { Debug.WriteLine(String.Format("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint)); Offline(); logger.Error("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint); return; } if (e.BytesTransferred == 0) { Close(); return; } ReceivedBytes += e.BytesTransferred - e.Offset; for (int i = e.Offset; i < e.Offset + e.BytesTransferred; i++) { try { frameStream.WriteByte(e.Buffer[i]); frameStream.Flush(); if (isNoCheck && noCheckCount > 0) { noCheckCount--; continue; } else if (isNoCheck) { isNoCheck = false; noCheckCount = 0; } if (!IsHandShake && Protocol.IsFrameEnd(frameStream)) { frameStream.Position = 0; HandshakeRequestCommand command = Protocol.GetCommand(this, frameStream) as HandshakeRequestCommand; HandshakeResponseCommand responseCmd = null; if (command != null) { ProtocolVersion = command.GetHeader(WebSocketHeader.SecWebSocketAccept) ?? ""; this.Url = command.GetHeader(WebSocketHeader.Url) ?? ""; frameStream.Position = 0; frameStream.SetLength(0); responseCmd = command.Execute(this) as HandshakeResponseCommand; if (responseCmd != null && !isClosed) { FrameReader = new FrameStreamReader(frameStream); } } if (responseCmd != null) { Protocol.WriteCommand(responseCmd, this); IsHandShake = true; OnHandshakeCompleted(); logger.Debug("客户端握手成功:{0} {1}", SessionID, EndPoint); } else { logger.Warn("客户端握手失败:{0} {1}", SessionID, EndPoint); this.Close(); } } else if (IsHandShake) { bool isSuccess = FrameReader.ProcessFrame(this); if (!isSuccess) { HttpCodeResponseCommand cmd = new HttpCodeResponseCommand(); cmd.SetHeader(WebSocketHeader.HttpCode, "1002"); sendOverClosed = true; Protocol.WriteCommand(cmd, this); logger.Error("接收数据帧发生异常:{0} {1}", SessionID, EndPoint); } else { // if (FrameReader.IsCompleted) { frameStream.Position = 0; frameStream.SetLength(0); logger.Trace("收到数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString()); FrameCommandBase command = WebSocketCommandFactory.CreateCommand(FrameReader); if (command != null) { command = command.Execute(this) as FrameCommandBase; if (command != null) { Protocol.WriteCommand(command, this); } } if (!this.isClosed) { FrameReader = new FrameStreamReader(frameStream); } } else if (FrameReader.IsContinue) { frameStream.Position = 0; frameStream.SetLength(0); FrameReader.Reset(); logger.Trace("收到持续数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString()); } } } } catch { break; } } if (!isClosed) { Protocol.TryGetCommand(this); } }
public bool AcceptAsync(ns.SocketAsyncEventArgs a) { return(realSocket.AcceptAsync(a)); }