Exemple #1
0
        /// <summary>
        /// 客户端连接初始化
        /// </summary>
        /// <param name="o"></param>
        private void Acceptor(IAsyncResult o)
        {
            TcpListener server = o.AsyncState as TcpListener;

            try
            {
                //初始化连接的客户端
                TCPClient newClient = new TCPClient();
                newClient.NetWork = server.EndAcceptTcpClient(o);
                AddTcpClient(newClient);                                          //添加缓存字典
                newClient.NetWork.GetStream().BeginRead(newClient.buffer, 0, newClient.buffer.Length, new AsyncCallback(TCPCallBack), newClient);
                server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server); //继续监听客户端连接
            }
            catch (ObjectDisposedException ex)
            { //监听被关闭
            }
            catch (Exception ex)
            {
                /// TraceManager.AppendErrMsg(ex.Message);
            }
        }
Exemple #2
0
        /// <summary>
        /// 对当前选中的客户端发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        public bool SendData(string clientName, byte[] data, out string errMsg)
        {
            errMsg = "";
            if (data == null)
            {
                errMsg = "发送数据对象为空对象,发送失败";
                return(false);
            }
            if (string.IsNullOrWhiteSpace(clientName))
            {
                errMsg = "发送的客户端对象为空对象,发送失败";
                return(false);
            }
            TCPClient client = QueryTcpClient(clientName);

            if (client == null)
            {
                errMsg = "发送的客户端对象为空对象,发送失败";
                return(false);
            }

            return(client.Send(data, out errMsg));
        }
        /// <summary>
        /// 连接新的服务端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool Connect(out string clientName, out string errMsg)
        {
            errMsg     = "";
            clientName = "";
            dicClients = new ConcurrentDictionary <string, TCPClient>();
            TCPClient client = new TCPClient();

            try
            {
                client.NetWork = new TcpClient();
                client.NetWork.Connect(this.ip.Trim(), this.port);//连接服务端
                client.SetName();
                client.NetWork.GetStream().BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client);
                this.dicClients.TryAdd(client.Name, client);
                clientName = client.Name;
                return(true);
            }
            catch (Exception ex)
            {
                client.DisConnect(out string ee);
                errMsg = ex.Message;
                return(false);
            }
        }
 // TCP 客户端增删改查
 private void AddTcpClient(TCPClient client)
 {
     this.dicClients.TryAdd(client.Name, client);
 }