protected override void Given() { MockSocketClient = Substitute.For <ISocketClient>(); SUT = new global::HAL.ControlLine.Sockets.ControlLineSockets( MockSocketClient ); }
private void Client_Disconnect(ISocketClient client, ZYSocket.ISockAsyncEventAsClient socketAsync, string msg) { this.BeginInvoke(new EventHandler((a, b) => { MessageBox.Show(msg); this.Close(); })); }
/// <summary> /// Initializes a new instance of <see cref="GraphQLWebSocketProtocol"/> /// </summary> /// <param name="socketClient"> /// The client where this protocol is using /// </param> public GraphQLWebSocketProtocol(ISocketClient socketClient) { _socketClient = socketClient ?? throw new ArgumentNullException(nameof(socketClient)); _receiver = new MessagePipeline(socketClient, ProcessAsync); _sender = new SynchronizedMessageWriter(socketClient); }
public SFSIOHandler(ISocketClient bitSwarm) { this.bitSwarm = bitSwarm as BitSwarmClient; log = bitSwarm.Log; packetEncrypter = new DefaultPacketEncrypter(this.bitSwarm); protocolCodec = new SFSProtocolCodec(this, bitSwarm); InitStates(); }
// for testing only internal SocketConnection(ISocketClient socketClient, IAuthToken authToken, ILogger logger, IMessageResponseHandler messageResponseHandler = null) { Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient)); _responseHandler = messageResponseHandler ?? new MessageResponseHandler(logger); _client = socketClient; _authToken = authToken; }
/// <summary>远程连接断开时触发。默认销毁整个会话,子类可根据业务情况决定客户端与代理的链接是否重用。</summary> /// <param name="session"></param> protected override void OnRemoteDispose(ISocketClient session) { // 如果客户端不要求保持连接,就销毁吧 if (!KeepAlive) { base.OnRemoteDispose(session); } }
//连接 public void Connect(string ip, int port, int type, LuaFunction callback) { if (true == isConnected) { //Debug.LogError("已经连接上了"); return; } m_IP = ip; m_Port = port; //不是同一个callback,释放掉 if (callback != m_LuaConnectCallback || false == callback.Equals(m_LuaConnectCallback)) { if (m_LuaConnectCallback != null) { m_LuaConnectCallback.Dispose(); } m_LuaConnectCallback = callback; m_ConnectAction = delegate(int errorCode, int reason) { m_LuaConnectCallback.Action <int, int>(errorCode, reason); }; } Debug.Log(" udp==0,tcp==1 当前尝试连接的类型 :" + type + "连接IP" + m_IP + "连接的端口:" + m_Port); if (0 == m_Port) { m_ConnErrorCode = ConnectErrorCode.Lost; return; } //放入待回收的池子 if (null != m_CurrentSocketClient) { m_CurrentSocketClient.Disconnect(); m_SocketList.Add(m_CurrentSocketClient); m_CurrentSocketClient = null; } switch ((CONNECT_TYPE)type) { case CONNECT_TYPE.Connect_Type_UDP: m_CurrentSocketClient = new UDPSocketClient(); break; case CONNECT_TYPE.Connect_Type_TCP: default: m_CurrentSocketClient = new TCPSocketClient(); break; } m_eReason = SOCKET_ERROR.SOCKET_ERROR_NON; ++m_nCurSocketID; m_CurrentSocketClient.SetSink(this); m_CurrentSocketClient.SetSocketID(m_nCurSocketID); //连接服务器 ReConnect(m_IP, m_Port); }
public SocketService(GM gameMaster, ISocketClient <Message, Message> client, GameConfiguration conf, BufferBlock <Message> queue, IApplicationLifetime lifetime, ILogger log) : base(gameMaster, log.ForContext <GMService>()) { this.client = client; this.conf = conf; this.queue = queue; this.lifetime = lifetime; }
public Server(ILog log) { _log = log; _client = new AsyncSocketClient(); _client.Log += (sender, args) => { _log.Log(args.Level, args.Message, args.Exception, args.Args); }; ReconnectAttempts = 0; }
private void Start() { //client = FlexiSocket.Create(ip, port, Protocol.StringTerminatedBy("\n", Encoding.UTF8)); client = FlexiSocket.Create(ip, port, Protocols.TotalLengthPrefix); client.Connected += ClientOnConnected; client.Disconnected += ClientOnDisconnected; client.ReceivedAsString += ClientOnReceivedAsString; client.Sent += ClientOnSent; }
public ServerlistManager() { _client = new TcpClient(new SessionFactory(), ArrayPool <byte> .Shared); _client.Pipeline.AddFirst("rmi", new SimpleRmiPipe()); _worker = new TaskLoop(Config.Instance.AuthAPI.UpdateInterval, Worker); _client.Connected += Client_Connected; _client.Disconnected += Client_Disconnected; }
public BaseController(ISocketClient socketClient) { this.socketClient = socketClient; if (socketClient != null) { log = socketClient.Log; sfs = socketClient.Sfs; } }
public static async Task ProcessConnect(this ISharkClient client, BlockData block, bool isFastConnect = false, byte[] challengeResp = null) { ISocketClient remote = null; BlockData resp = new BlockData() { Type = BlockType.CONNECTED, Id = block.Id }; if (isFastConnect) { if (challengeResp == null) { throw new ArgumentNullException(nameof(challengeResp), "challege response cannot be null in fast conenct request"); } var buffer = new byte[4 + challengeResp.Length]; BitConverter.TryWriteBytes(buffer, client.Id); challengeResp.CopyTo(buffer, 4); resp.Data = buffer; } try { client.Logger.LogInformation("Process connect {0}", block.Id); var host = JsonSerializer.Deserialize <HostData>(Encoding.UTF8.GetString(block.Data.Span)); remote = await client.ConnectTo(host.Address, host.Port, host.Type, block.Id); client.Logger.LogInformation("Connected {0}", block.Id); } catch (Exception) { client.Logger.LogError("Connect failed {0}", block.Id); resp.Type = BlockType.CONNECT_FAILED; if (remote != null) { remote.Dispose(); client.RemoteClients.Remove(remote.Id); } } try { client.EncryptBlock(ref resp); await client.WriteBlock(resp); if (resp.Type == BlockType.CONNECTED) { client.RunRemoteLoop(remote); } } catch (Exception e) { client.Logger.LogError(e, "Shark errored"); client.Dispose(); } }
private void DoStart(ISocketClient serverClient) { try { OnStart(serverClient); } catch (Exception) { } }
public static INodeSharpClient Create(ISocketClient socket, string nodeExePath, string nodeJsPath) { var process = SpawnProcess(nodeExePath, nodeJsPath); socket.Connect(); return(new NodeSharpClient { Socket = socket, NodeProcess = process }); }
public void Close() { if (_socket == null) { return; } _socket.Close(); _socket = null; }
protected override void WhenClientConnects(ISocketClient client) { base.WhenClientConnects(client); client.Send(Encoding.ASCII.GetBytes("\u00B1[?3l")); // columns to 80 Task.Run(async() => { await _streamer.StreamToClient(client); }); }
public DefaultTransportFactory(ISocketClient <AmpMessage> socket, IClientMessageHandler <AmpMessage> handler) { this._socket = socket; this._handler = handler; this._socket.OnIdleState += _socket_OnIdleState; this._socket.OnReceived += _socket_OnReceived; this._socket.OnConnected += _socket_OnConnected; this._socket.OnDisconnected += _socket_OnDisconnected; this._socket.OnError += _socket_OnError; }
/// <summary>连接后自动登录</summary> /// <param name="client">客户端</param> /// <param name="force">强制登录</param> protected override async Task <Object> OnLoginAsync(ISocketClient client, Boolean force) { if (Logined && !force) { return(null); } Logined = false; var user = UserName; var pass = Password; //if (user.IsNullOrEmpty()) return null; //if (user.IsNullOrEmpty()) throw new ArgumentNullException(nameof(user), "用户名不能为空!"); //if (pass.IsNullOrEmpty()) throw new ArgumentNullException(nameof(pass), "密码不能为空!"); if (!pass.IsNullOrEmpty()) { pass = pass.MD5(); } var arg = new { user, pass, }; // 克隆一份,避免修改原始数据 var dic = arg.ToDictionary(); dic.Merge(GetLoginInfo(), false); var act = "Login"; if (!ActionPrefix.IsNullOrEmpty()) { act = ActionPrefix + "/" + act; } var rs = await base.InvokeWithClientAsync <Object>(client, act, dic); var inf = rs.ToJson(); XTrace.WriteLine("登录{0}成功!{1}", Servers.FirstOrDefault(), inf); Logined = true; Info = rs as IDictionary <String, Object>; if (_timer == null) { _timer = new TimerX(DoPing, null, 10_000, 30_000); } return(rs); }
public SocketService(ISocketClient <Message, Message> client, PlayerConfiguration conf, BufferBlock <Message> queue, IApplicationLifetime lifetime, ILogger log, ServiceSynchronization serviceSync) { this.client = client; this.conf = conf; this.queue = queue; this.lifetime = lifetime; this.logger = log.ForContext <SocketService>(); this.synchronizationContext = serviceSync; }
///// <summary>创建消息</summary> ///// <param name="pk"></param> ///// <returns></returns> //IMessage IApiSession.CreateMessage(Packet pk) => new DefaultMessage { Payload = pk }; async Task <Tuple <IMessage, Object> > IApiSession.SendAsync(IMessage msg) { Exception last = null; ISocketClient client = null; var count = Servers.Length; for (var i = 0; i < count; i++) { try { try { //client = Pool.Get(); client = GetClient(); var rs = (await client.SendMessageAsync(msg)) as IMessage; return(new Tuple <IMessage, Object>(rs, client)); } catch (ApiException ex) { // 重新登录 if (ex.Code == 401) { OnLogin(client); var rs = (await client.SendMessageAsync(msg)) as IMessage; return(new Tuple <IMessage, Object>(rs, client)); } else { throw; } } } catch (ApiException) { throw; } catch (Exception ex) { last = ex; client.TryDispose(); //client = null; } //finally //{ // if (client != null) Pool.Put(client); //} } if (ShowError) { WriteLog("请求[{0}]错误!Timeout=[{1}ms] {2}", client, Timeout, last?.GetMessage()); } throw last; }
StunMessage Query(ISocketClient client, StunMessage request, IPEndPoint remoteEndPoint) { Packet pk = null; try { if (client.Local.IsTcp) { // Tcp协议不支持更换IP或者端口 if (request.ChangeIP || request.ChangePort) { return(null); } //if (!client.Connected) client.Connect(remoteEndPoint); //client.Send(request.ToArray()); } //else // client.SendTo(request.ToArray(), remoteEndPoint); WriteLog("查询 {0} =>{1}", request, remoteEndPoint); client.Remote.EndPoint = remoteEndPoint; client.Send(request.ToArray()); pk = client.Receive(); if (pk == null || pk.Count == 0) { return(null); } } catch { return(null); } var rs = StunMessage.Read(pk.GetStream()); //if (rs != null && rs.Type != StunMessageType.BindingResponse) return null; if (rs == null) { return(null); } // 不是同一个会话不要 if (!rs.TransactionID.SequenceEqual(request.TransactionID)) { return(null); } // 不是期望的响应不要 if (rs.Type != (StunMessageType)((UInt16)request.Type | 0x0100)) { return(null); } return(rs); }
public void Open() { if (Client == null || Client.Disposed) { Client = Remote.CreateRemote(); Client.Received += Client_Received; Client.Open(); SendPack("Name", Name); } }
public Player(PlayerConfiguration conf, BufferBlock <Message> queue, ISocketClient <Message, Message> client, ILogger log) { this.conf = conf; this.strategy = StrategyFactory.Create((StrategyEnum)conf.Strategy, this, log); this.queue = queue; this.client = client; this.logger = log.ForContext <Player>(); this.Team = conf.TeamID; this.Position = (-1, -1); }
public async Task DisconnectAsync() { lock (this) { if (!Connected) { AddStatusMessage(StatusMessageTypes.Warning, "Can not disconnected - Not Connected"); return; } Mode = OperatingMode.Disconnected; Connected = false; MachinePosition = new Vector3(); WorkspacePosition = new Vector3(); Status = "Disconnected"; DistanceMode = ParseDistanceMode.Absolute; Unit = ParseUnit.Metric; Plane = ArcPlane.XY; UnacknowledgedBytesSent = 0; lock (_queueAccessLocker) { _toSend.Clear(); _toSendPriority.Clear(); _sentQueue.Clear(); } } if (_port != null) { await _port.CloseAsync(); AddStatusMessage(StatusMessageTypes.Info, "Closed Serial Port"); _port = null; } if (_socketClient != null) { await _socketClient.CloseAsync(); _socketClient.Dispose(); _socketClient = null; } if (this._cancelSource != null) { _cancelSource.Cancel(); _cancelSource = null; } AddStatusMessage(StatusMessageTypes.Info, "Disconnected"); }
public void Constructor_ClientNull_ThrowException() { // arrange ISocketClient client = null !; // act Exception?exception = Record.Exception(() => new Session(client)); // assert Assert.IsType <ArgumentNullException>(exception); }
private void OnDestroy() { mSocketClient.Close(); mSocketClient = null; UnsubscribeEvent(); // BluetoothLEHardwareInterface.DeInitialize (delegate { // }); }
// Use this for initialization private IEnumerator Start() { _client = FlexiSocket.Create("localhost", 1366, Protocols.BodyLengthPrefix); _client.Connected += OnConnected; _client.Disconnected += OnDisconnected; _client.Received += OnReceived; _client.Sent += OnSent; yield return(new WaitForSeconds(1)); _client.Connect(); }
/// <summary> /// Subscribes to a <see cref="ISocketClient"/> to receive data and pipes the received /// messages separated by a delimiter into a pipe. /// </summary> /// <param name="writer">The writer the message to write to</param> /// <param name="client">The client to subscribe to</param> /// <param name="cancellationToken">The cancellation token that stops the receiving</param> /// <returns> /// A tasks that stops when <paramref name="cancellationToken"/> is cancelled /// </returns> public static Task Start( PipeWriter writer, ISocketClient client, CancellationToken cancellationToken) { return(Task.Factory.StartNew( () => ReceiveAsync(client, writer, cancellationToken), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }
public SocketConnection(ISocketClient socketClient, IAuthToken authToken, ILogger logger, IMessageResponseHandler messageResponseHandler = null) { Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient)); _messageHandler = messageResponseHandler ?? new MessageResponseHandler(logger); _client = socketClient; Task.Run(() => _client.Start()).Wait(); // add init requestMessage by default Enqueue(new InitMessage("neo4j-dotnet/1.0.0", authToken.AsDictionary())); }
void Dispose(Boolean disposing) { if (disposed) return; disposed = true; if (disposing) GC.SuppressFinalize(this); //XTrace.WriteLine("{0}被抛弃!{1} {2}", ID, LastOperation, RemoteIPEndPoint); //! 清空缓冲区,这一点非常非常重要,内部有个重叠数据对象,挂在一个全局对象池上,它会Pinned住数据缓冲区,这里必须清空被Pinned住的缓冲区 SetBuffer(0); // 断开所有资源的链接 _buffer = null; _Socket = null; _Session = null; _Error = null; base.Dispose(); }
/* public Task<int> Send(string data) { try { byte[] b = Encoding.UTF8.GetBytes(data); return Send(b); } catch (Exception ex) { RaiseError(ex); throw; } } public Task<int> Send(byte[] data) { try { _tosend.Enqueue(data); return Flush(); } catch (Exception ex) { RaiseError(ex); throw; } } public Task<int> Flush() { try { if (_socket == null) return Task<int>.FromResult(0); if (_tosend.IsEmpty) return Task<int>.FromResult(0); var tcs = new TaskCompletionSource<int>(_socket); List<byte> send = new List<byte>(); byte[] data; while (_tosend.TryDequeue(out data)) { send.AddRange(data); } if (send.Count > 0) { data = send.ToArray(); _socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) => { try { var t = (TaskCompletionSource<int>)ar.AsyncState; var s = (Socket)t.Task.AsyncState; try { int sent = s.EndSend(ar); t.TrySetResult(sent); RaiseSent(sent); } catch (Exception exc) { RaiseError(exc); t.TrySetException(exc); } } catch (Exception ex) { RaiseError(ex); } }, tcs); } else { tcs.TrySetResult(0); } return tcs.Task; } catch (Exception ex) { RaiseError(ex); throw; } } */ void HandleClient(ISocketClient client) { client.Disconnected += (sender, b) => { _clients.Remove(client); RaiseDisconnected(client); }; client.Error += (sender, err) => { RaiseError(err.Value); }; client.ReceivedData += (sender, args) => { RaiseReceivedData(client, args.Data, args.Size); }; client.Sent += (sender, sent) => { RaiseSent(sent.Value); }; Task.Factory.StartNew(() => { while (client.IsConnected) { client.Receive().Wait(); } }); }
void EnsureSocket2() { if (_Socket2 == null) { var socket = Socket.Client; var ep = socket.LocalEndPoint as IPEndPoint; var sto = socket.SendTimeout; var rto = socket.ReceiveTimeout; // 如果原端口没有启用地址重用,则关闭它 Object value = socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress); if (!Convert.ToBoolean(value)) socket.Close(); //var sk = NetService.Container.Resolve<ISocketClient>(socket.ProtocolType); ////sk.Address = ep.Address; ////sk.Port = ep.Port; //sk.Local.EndPoint = ep; var sk = new NetUri((NetType)socket.ProtocolType, ep).CreateClient(); sk.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //sk.Bind(); sk.Client.SendTimeout = sto; sk.Client.ReceiveTimeout = rto; _Socket2 = sk; } }
void RaiseDisconnected(ISocketClient client) { if (Disconnected != null) Disconnected(this, new EventArgs<ISocketClient>(client)); }
void RaiseReceivedData(ISocketClient client, byte[] data, int length) { if (ReceivedData != null) ReceivedData(this, new SocketDataArgs(client, data, length)); }
public GameNetworkClient(ISocketClient socketClient) { _socketClient = socketClient; _socketClient.Received += socketClientOnReceived; }
// 如果是外部传进来的Socket,也销毁,就麻烦大了 ///// <summary>子类重载实现资源释放逻辑时必须首先调用基类方法</summary> ///// <param name="disposing">从Dispose调用(释放所有资源)还是析构函数调用(释放非托管资源)</param> //protected override void OnDispose(bool disposing) //{ // base.OnDispose(disposing); // if (_Socket != null) // { // _Socket.Dispose(); // _Socket = null; // } // if (_Socket2 != null) // { // _Socket2.Dispose(); // _Socket2 = null; // } //} #endregion #region 方法 void EnsureSocket() { if (_Socket == null) { //var client = NetService.Container.Resolve<ISocketClient>(ProtocolType); //client.Port = Port; var client = new NetUri(ProtocolType, "", Port).CreateClient(); client.Open(); client.Client.SendTimeout = Timeout; client.Client.ReceiveTimeout = Timeout; _Socket = client; } }
public SocketDataArgs(ISocketClient client, byte[] data, int size) { Client = client; Data = data; Size = size; }
static void Publish(ISocketClient client, string data, int count) { try { if (System.IO.File.Exists(data)) { data = System.IO.File.ReadAllText(data); } for (int i = 0; i < count && client.IsConnected; i++) { string msg = string.Format(data, i); Debug("DOTNET-SOCKET Client: Sending {0}", i); client.Send(msg).Wait(); } } catch (Exception ex) { Error("DOTNET-SOCKET Client", ex); } finally { } }
/// <summary> /// /// </summary> /// <returns></returns> public static IEnumerator StartVRClient(ISocketClient socketClient) { //keep the client from sending video until we have connected blnSendingScreenShot = true; int intADBProcExitCode = 0; string strADBProcStatus = ""; //have the android debug bridge run port forwarding so we can use this port //to send data over the USB intADBProcExitCode = RunADBPortForward2(ViewerConstants.PORT, ref strADBProcStatus); yield return 0; UnityEngine.Debug.Log("ADB Port Forward exit code : " + intADBProcExitCode + " status : " + strADBProcStatus); //connect to the server on the Android using USB ClientControl.Instance.Init(ViewerConstants.LocalHost, ViewerConstants.PORT, ProtocolType.Tcp, socketClient); //tell the client it is okay to send video now. we should be connected. blnSendingScreenShot = false; yield return 0; }
static void Subscribe(ISocketClient client, int countlog) { try { while (client.IsConnected) { Debug("DOTNET-SOCKET Client: Waiting for data"); client.Receive().Wait(); } } catch (Exception ex) { Error("DOTNET-SOCKET Client", ex); } finally { } }
StunMessage Query(ISocketClient client, StunMessage request, IPEndPoint remoteEndPoint) { Byte[] buffer = null; try { if (client.Local.IsTcp) { // Tcp协议不支持更换IP或者端口 if (request.ChangeIP || request.ChangePort) return null; //if (!client.Connected) client.Connect(remoteEndPoint); //client.Send(request.ToArray()); } //else // client.SendTo(request.ToArray(), remoteEndPoint); WriteLog("查询 {0} =>{1}", request, remoteEndPoint); client.Remote.EndPoint = remoteEndPoint; client.Send(request.ToArray()); buffer = client.Receive(); if (buffer == null || buffer.Length == 0) return null; } catch { return null; } var rs = StunMessage.Read(new MemoryStream(buffer)); //if (rs != null && rs.Type != StunMessageType.BindingResponse) return null; if (rs == null) return null; // 不是同一个会话不要 if (rs.TransactionID.CompareTo(request.TransactionID) != 0) return null; // 不是期望的响应不要 if (rs.Type != (StunMessageType)((UInt16)request.Type | 0x0100)) return null; return rs; }