internal override void CloseConnection(Exception ex, IConnection remoteHost) { if (!SocketMap.TryGetValue(remoteHost.RemoteHost, out var clientSocket)) { return; } try { if (clientSocket.Socket.Connected) { clientSocket.Socket.Close(); } } catch (Exception innerEx) { OnErrorIfNotNull(innerEx, remoteHost); } finally { NodeDisconnected(new HeliosConnectionException(ExceptionType.Closed, ex), remoteHost); SocketMap.TryRemove(remoteHost.RemoteHost, out var temp); if (!clientSocket.WasDisposed) { clientSocket.Dispose(); } } }
private void SendCallback(IAsyncResult ar) { var receiveState = (NetworkState)ar.AsyncState; try { var bytesSent = receiveState.Socket.EndSend(ar); receiveState.Buffer.SkipBytes(bytesSent); if (receiveState.Buffer.ReadableBytes > 0) //need to send again { receiveState.Socket.BeginSendTo(receiveState.Buffer.ToArray(), 0, receiveState.Buffer.ReadableBytes, SocketFlags.None, receiveState.RemoteHost.ToEndPoint(), SendCallback, receiveState); } } catch (SocketException ex) //node disconnected { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(ex, connection); } } catch (Exception ex) { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; OnErrorIfNotNull(ex, connection); } } }
public static IApplicationBuilder UseSocket(this IApplicationBuilder app, SocketMap map) { Manager = new ConnectionManager(map); app.UseWebSockets(); app.Use(async (http, next) => { ITicketManager ticket = Kernel.Resolve<ITicketManager>(); if (http.WebSockets.IsWebSocketRequest && ticket.IsAuthenticated) { var webSocket = await http.WebSockets.AcceptWebSocketAsync(); if (webSocket != null && webSocket.State == WebSocketState.Open) { await Manager.Add(ticket.UserKey.ToString(), webSocket); } } else { await next(); } }); return app; }
internal override void CloseConnection(Exception ex, IConnection remoteHost) { if (!SocketMap.ContainsKey(remoteHost.RemoteHost)) { return; //already been removed } var clientSocket = SocketMap[remoteHost.RemoteHost]; try { if (clientSocket.Socket.Connected) { clientSocket.Socket.Close(); } } catch (Exception innerEx) { OnErrorIfNotNull(innerEx, remoteHost); } finally { NodeDisconnected(new HeliosConnectionException(ExceptionType.Closed, ex), remoteHost); if (SocketMap.ContainsKey(remoteHost.RemoteHost)) { SocketMap.Remove(remoteHost.RemoteHost); } if (!clientSocket.WasDisposed) { clientSocket.Dispose(); } } }
/// <summary> /// 关闭连接 /// </summary> /// <param name="reason"></param> /// <param name="remoteConnection"></param> internal override void CloseConnection(Exception reason, IConnection remoteConnection) { Console.WriteLine("CloseConnection-->>" + reason.ToString() + remoteConnection.ToString()); if (SocketMap.ContainsKey(remoteConnection.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[remoteConnection.RemoteHost.nodeConfig.ToString()]; CloseConnection(connection); } }
public ConnectionManager(SocketMap map) { Connections = new List<ConnectionItem>(); Map = map; Map.SendMessageAll += async (s, e) => await SendAll(new SocketMessage(string.Empty, e.Item1, JsonConvert.SerializeObject(e.Item2))); Map.SendMessageTo += async (s, e) => await SendTo(e.Item1, new SocketMessage(e.Item2, JsonConvert.SerializeObject(e.Item3))); Map.SendMessageAllExcept += async (s, e) => await SendAllExcept(e.Item1, new SocketMessage(e.Item2, JsonConvert.SerializeObject(e.Item3))); }
///// <summary> /// 处理数据 /// </summary> /// <param name="receiveState"></param> private void ReceiveCallback(IAsyncResult ar) { var receiveState = (NetworkState)ar.AsyncState; try { var received = ListenerSocket.EndReceiveFrom(ar, ref RemoteEndPoint); if (received == 0) { return; } var remoteAddress = (IPEndPoint)RemoteEndPoint; receiveState.RemoteHost = remoteAddress.ToNode(ReactorType.Udp); INode node = receiveState.RemoteHost; if (SocketMap.ContainsKey(receiveState.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; node = connection.RemoteHost; } else { RefactorRequestChannel requestChannel = new RefactorProxyRequestChannel(this, node, "none"); SocketMap.Add(node.nodeConfig.ToString(), requestChannel); } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out List <IByteBuf> decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); LogAgent.Info(String.Format("Socket收到数据-->>{0}", this.Encoder.ByteEncode(networkData.Buffer))); if (ConnectionAdapter is ReactorConnectionAdapter) { ((ReactorConnectionAdapter)ConnectionAdapter).networkDataDocker.AddNetworkData(networkData); ((EventWaitHandle)((ReactorConnectionAdapter)ConnectionAdapter).protocolEvents[(int)ProtocolEvents.PortReceivedData]).Set(); } } //清除数据继续接收 receiveState.RawBuffer = new byte[receiveState.RawBuffer.Length]; ListenerSocket.BeginReceiveFrom(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ref RemoteEndPoint, ReceiveCallback, receiveState); } catch //node disconnected { if (SocketMap.ContainsKey(receiveState.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; CloseConnection(connection); } } }
private void AcceptCallback(IAsyncResult ar) { var newSocket = Listener.EndAccept(ar); var node = NodeBuilder.FromEndpoint((IPEndPoint)newSocket.RemoteEndPoint); var receiveState = CreateNetworkState(newSocket, node); var responseChannel = new TcpReactorResponseChannel(this, newSocket, EventLoop.Clone(ProxiesShareFiber)); SocketMap.Add(node, responseChannel); NodeConnected(node, responseChannel); newSocket.BeginReceive(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ReceiveCallback, receiveState); Listener.BeginAccept(AcceptCallback, null); //accept more connections }
/// <summary> /// 开始监听 /// </summary> protected override void StartInternal() { IsActive = true; if (!SocketMap.ContainsKey(this.LocalEndpoint.nodeConfig.ToString())) { RefactorRequestChannel adapter = new RefactorProxyRequestChannel(this, this.LocalEndpoint, "none"); SocketMap.Add(this.LocalEndpoint.nodeConfig.ToString(), ConnectionAdapter); } IsActive = true; ListenerSocket.Bind(LocalEndPoint); ListenerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); ListenerSocket.BeginReceiveFrom(this.networkState.RawBuffer, 0, this.networkState.RawBuffer.Length, SocketFlags.None, ref RemoteEndPoint, PortDataReceived, this.networkState); }
/// <summary> /// 开始监听 /// </summary> protected override void StartInternal() { var receiveState = CreateNetworkState(Listener, Node.Empty()); if (!SocketMap.ContainsKey(this.LocalEndpoint.nodeConfig.ToString())) { RefactorRequestChannel adapter; adapter = new RefactorProxyRequestChannel(this, this.LocalEndpoint, "none"); SocketMap.Add(this.LocalEndpoint.nodeConfig.ToString(), adapter); } ListenerSocket.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived); ListenerSocket.Open(); IsActive = true; }
internal override void CloseConnection(Exception reason, IConnection remoteConnection) { //NO-OP (no connections in UDP) try { NodeDisconnected(new HeliosConnectionException(ExceptionType.Closed, reason), remoteConnection); } catch (Exception innerEx) { OnErrorIfNotNull(innerEx, remoteConnection); } finally { SocketMap.TryRemove(remoteConnection.RemoteHost, out var temp); } }
/// <summary> /// 处理数据 /// </summary> /// <param name="receiveState"></param> private void ReceiveCallback(NetworkState receiveState) { try { var received = receiveState.RawBuffer.Length; if (received == 0) { return; } INode node = receiveState.RemoteHost; if (SocketMap.ContainsKey(receiveState.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; node = connection.RemoteHost; } else { RefactorProxyResponseChannel adapter = new RefactorProxyResponseChannel(this, null); SocketMap.Add(adapter.RemoteHost.nodeConfig.ToString(), adapter.requestChannel); } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); List <IByteBuf> decoded; Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); string log = String.Format("{0}:串口处理数据-->>{1}", DateTime.Now.ToString("hh:mm:ss"), this.Encoder.ByteEncode(networkData.Buffer)); Console.WriteLine(log); if (ConnectionAdapter is ReactorConnectionAdapter) { ((ReactorConnectionAdapter)ConnectionAdapter).networkDataDocker.AddNetworkData(networkData); ((EventWaitHandle)((ReactorConnectionAdapter)ConnectionAdapter).protocolEvents[(int)ProtocolEvents.PortReceivedData]).Set(); } } } catch //node disconnected { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; CloseConnection(connection); } }
public override void Send(byte[] buffer, int index, int length, INode destination) { if (!SocketMap.TryGetValue(destination, out var clientSocket)) { return; } try { if (clientSocket.WasDisposed || !clientSocket.Socket.Connected) { CloseConnection(clientSocket); return; } var buf = Allocator.Buffer(length); buf.WriteBytes(buffer, index, length); List <IByteBuf> encodedMessages; clientSocket.Encoder.Encode(ConnectionAdapter, buf, out encodedMessages); foreach (var message in encodedMessages) { var bytesToSend = message.ToArray(); var bytesSent = 0; while (bytesSent < bytesToSend.Length) { bytesSent += clientSocket.Socket.Send(bytesToSend, bytesSent, bytesToSend.Length - bytesSent, SocketFlags.None); } HeliosTrace.Instance.TcpInboundClientSend(bytesSent); HeliosTrace.Instance.TcpInboundSendSuccess(); } } catch (SocketException ex) { HeliosTrace.Instance.TcpClientSendFailure(); CloseConnection(ex, clientSocket); } catch (Exception ex) { HeliosTrace.Instance.TcpClientSendFailure(); OnErrorIfNotNull(ex, clientSocket); } }
private void AcceptCallback(IAsyncResult ar) { try { var newSocket = Listener.EndAccept(ar); var node = NodeBuilder.FromEndpoint((IPEndPoint)newSocket.RemoteEndPoint); HeliosTrace.Instance.TcpInboundAcceptSuccess(); var receiveState = CreateNetworkState(newSocket, node); var responseChannel = new TcpReactorResponseChannel(this, newSocket, EventLoop.Clone(ProxiesShareFiber)); SocketMap.TryAdd(node, responseChannel); NodeConnected(node, responseChannel); newSocket.BeginReceive(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ReceiveCallback, receiveState); Listener.BeginAccept(AcceptCallback, null); //accept more connections } catch (Exception ex) { HeliosTrace.Instance.TcpInboundAcceptFailure(ex.Message); } }
public void ReadFile() { Console.Write("Please enter a file location for NetworkArchitect: "); string fileLocation = Console.ReadLine(), line = ""; fileLocation = FileUtility.CheckFileLocation(fileLocation); StreamReader stream = new StreamReader(fileLocation); for (int i = 0; (line = stream.ReadLine()) != null; i++) { if (i == 0) //Sockets { AddSockets(line); } else { AddSocketConnections(line); } } socketMap = new SocketMap(verticesAmount, edgesAmount); AddSocketToTree(); DisplaySockets(); }
private void ReceiveCallback(IAsyncResult ar) { var receiveState = (NetworkState)ar.AsyncState; try { var received = receiveState.Socket.EndReceiveFrom(ar, ref RemoteEndPoint); if (received == 0) { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(connection); } return; } var remoteAddress = (IPEndPoint)RemoteEndPoint; if (receiveState.RemoteHost.IsEmpty()) { receiveState.RemoteHost = remoteAddress.ToNode(TransportType.Udp); } ReactorResponseChannel adapter; if (SocketMap.ContainsKey(receiveState.RemoteHost)) { adapter = SocketMap[receiveState.RemoteHost]; } else { adapter = new ReactorProxyResponseChannel(this, receiveState.Socket, remoteAddress, EventLoop.Clone(ProxiesShareFiber)); ; SocketMap.Add(adapter.RemoteHost, adapter); NodeConnected(adapter.RemoteHost, adapter); } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); List <IByteBuf> decoded; Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); ReceivedData(networkData, adapter); } //reuse the buffer if (receiveState.Buffer.ReadableBytes == 0) { receiveState.Buffer.SetIndex(0, 0); } else { receiveState.Buffer.CompactIfNecessary(); } receiveState.Socket.BeginReceiveFrom(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ref RemoteEndPoint, ReceiveCallback, receiveState); //receive more messages } catch (SocketException ex) //node disconnected { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(ex, connection); } catch (ObjectDisposedException ex) { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(ex, connection); } } catch (Exception ex) { var connection = SocketMap[receiveState.RemoteHost]; OnErrorIfNotNull(ex, connection); } }
private void ReceiveCallback(IAsyncResult ar) { var receiveState = (NetworkState)ar.AsyncState; try { var received = receiveState.Socket.EndReceive(ar); if (!receiveState.Socket.Connected || received == 0) { HeliosTrace.Instance.TcpInboundReceiveFailure(); var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(connection); return; } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); HeliosTrace.Instance.TcpInboundReceive(received); var adapter = SocketMap[receiveState.RemoteHost]; List <IByteBuf> decoded; adapter.Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); ReceivedData(networkData, adapter); HeliosTrace.Instance.TcpInboundReceiveSuccess(); } //reuse the buffer if (receiveState.Buffer.ReadableBytes == 0) { receiveState.Buffer.SetIndex(0, 0); } else { receiveState.Buffer.CompactIfNecessary(); var postCompact = receiveState.Buffer; } //continue receiving in a loop receiveState.Socket.BeginReceive(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ReceiveCallback, receiveState); } catch (SocketException ex) //node disconnected { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(ex, connection); } HeliosTrace.Instance.TcpInboundReceiveFailure(); } catch (ObjectDisposedException ex) { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; CloseConnection(ex, connection); } HeliosTrace.Instance.TcpInboundReceiveFailure(); } catch (Exception ex) { if (SocketMap.ContainsKey(receiveState.RemoteHost)) { var connection = SocketMap[receiveState.RemoteHost]; OnErrorIfNotNull(ex, connection); } HeliosTrace.Instance.TcpInboundReceiveFailure(); } }
void server_OnClientConnectEvent(object sender, ConnectEventArgs args) { if (args.client != null) { ClientSocket from = args.client; string[] ap = from.sRemoteIPAndPort.Split(':'); string addr = ap[0]; int port = Convert.ToInt32(ap[1]); if (!portRef.ContainsKey(port)) { portRef.Add(port, new List <ClientSocket>()); //Logs.Create("有新Socket连接:" + from.sRemoteIPAndPort + ",加入动态映射端口列表中"); } try { MapManager.LoadMap(); List <int> froms = MapManager.Map.GetFromPort(port); if (froms.Count > 0) { foreach (int p in portRef.Keys) { if (froms.Contains(p)) { portRef[p].Add(from); //Logs.Create("有新Socket连接:" + from.sRemoteIPAndPort + ",加入动态映射引用列表中"); } else { //非法连接,自动忽略 } } } } catch (Exception ex) { Logs.Create("查询数据库中的映射配置时出错:" + ex.Message); } finally { MapManager.Dispose(); } if (!portMap.ContainsKey(from)) { SocketMap map = new SocketMap(new AddressAndPort() { Address = addr, Port = port }); portMap.Add(from, map); //Logs.Create("有新Socket连接:" + from.sRemoteIPAndPort + ",加入动态映射起点列表中"); } foreach (int p in portRef.Keys) { foreach (ClientSocket c in portRef[p]) { foreach (ClientSocket f in portMap.Keys) { int po = Convert.ToInt32(f.sRemoteIPAndPort.Split(':')[1]); if (po == p && !portMap[from].Clients.Contains(c)) { portMap[f].Clients.Add(c); //Logs.Create("有合法的映射终点Socket连接:" + from.sRemoteIPAndPort + ",加入动态映射终点列表中"); } } } } //Console.WriteLine(String.Format("{0} 连接.", args.client.sRemoteIPAddress)); //SocketServer server = (SocketServer)sender; //if (server.ClientCount > 1) //{ // foreach (var item in mClients) // { // System.Net.Sockets.SocketInformation mInfomation = args.client.cSocket.DuplicateAndClose(item.ProcessId); // ChangeObject mObject = new ChangeObject // { // PackType = (int)Common.ECommand.SocketInfo, // SerialNumber = 0, // mData = Common.SerializeSocketInfo(mInfomation) // }; // mObject.PackLength = 12 + mObject.mData.Length; // byte[] mBytes = mObject.ToBuffer(); // server.SendData(item.cSocket.SocketID, mBytes); // break; // } //} } }