Example #1
0
        private void SocketTcpServer_ClientConnected(UserToken token)
        {
            try
            {
                _logger.LogInformation($"client connect [{token.Remote}]");
                SetSocketKey(token);
                string key = token.Key;
                if (!string.IsNullOrEmpty(key))
                {
                    //其它设备类型连接进来直接关闭
                    if (token.DeviceType == 0)
                    {
                        token.Socket.Shutdown(SocketShutdown.Send);
                        return;
                    }
                    if (_socketClientDictionary.ContainsKey(key))
                    {
                        //如果同一对象2次连接 关闭前一次连接
                        var socket = _socketClientDictionary[key].Socket;
                        if (socket.Connected)
                        {
                            socket.Shutdown(SocketShutdown.Send);
                        }
                        _socketClientDictionary[key] = token;
                    }
                    else
                    {
                        _socketClientDictionary.Add(key, token);
                    }

                    DeviceStateSend(token, 0);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.InnerException?.Message ?? e.Message);
            }
        }
Example #2
0
        public void SendMessage(string id, byte[] bytes, bool isAddCheck = true)
        {
            if (!_socketClientDictionary.ContainsKey(id))
            {
                return;
            }
            var userToken = _socketClientDictionary[id];

            if (userToken != null)
            {
                if (userToken.Socket == null || !userToken.Socket.Connected)
                {
                    return;
                }
                try
                {
                    var sendBytes = bytes;
                    if (isAddCheck)
                    {
                        IList <byte> byteList = new List <byte>(bytes)
                        {
                            ConstDefine.CheckUserId
                        };
                        sendBytes = byteList.ToArray();
                    }
                    _logger.LogInformation($"s [{userToken.Remote}]:{CommonHelper.BytesToHexStr(sendBytes)}");
                    //新建异步发送对象, 发送消息
                    SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs {
                        UserToken = userToken
                    };
                    sendArg.SetBuffer(sendBytes, 0, sendBytes.Length);
                    userToken.Socket.SendAsync(sendArg);
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"s [{userToken.Remote}] fail:{ex.Message}");
                }
            }
        }