//向客户端发送数据 public void Send(TcpClientEx tcpClient, ArraySegment <byte> datas) { if (tcpClient != null && tcpClient.Connected) { try { NetworkStream stream = tcpClient.GetStream(); if (stream != null) { int num = 0; while (!stream.CanWrite && tcpClient != null && tcpClient.Connected) { num++; if (num > 10) { return; } Thread.Sleep(1000); continue; } SplitPakeage splitPakeage = new SplitPakeage(); byte[] newData = splitPakeage.AssembleBytes(datas, this); stream.WriteAsync(newData, 0, newData.Length); stream.Flush(); TcpPackConfig.SendDelayTime(); } } catch { } } }
/// <summary> /// /// </summary> /// <param name="content"></param> /// <param name="destUserId"></param> public void Send(string content, int destUserId) { #region TcpClientEx tcpclient = ChatClient.ConnectServer(); ChatContent contentobj = new ChatContent() { _FromUID = int.Parse(Logon._User.uid), _Text = content, _ToUId = destUserId }; SendChatContent sendchatcontent = new SendChatContent() { _Content = contentobj }; byte[] command = sendchatcontent.GetProtocolCommand(); tcpclient.SendToEndDevice(command); //可接收是否发送成功 /* * tcpclient.Receive(); * * RecvUserCheckResult usercheckresult = new RecvUserCheckResult(); * * tcpclient.Dispatcher(usercheckresult); */ tcpclient.Close(); #endregion }
private static void LogicRun() { g_client = new Dictionary <IntPtr, Session>(); for (int i = startId; i < endId; i++) { TcpClientEx client = new TcpClientEx("127.0.0.1", 13006, 5, OnSocket); Session s = new Session(client); if (client.Connect(true)) { s.SocketState = SocketState.CHECKING; s.ID = i; s.SendFirstSelfSalt(); //s.LoginGame("soul" + i.ToString(), "0000", "魔域"); g_client[client.ConnectionId] = s; } } while (true) { Dictionary <IntPtr, Session> dic = new Dictionary <IntPtr, Session>(g_client); foreach (Session client in dic.Values) { client.Run(); } System.Threading.Thread.Sleep(4); } }
public void BeginAcceptClients() { Task.Run(async() => { while (true) { try { var ex = await listener.AcceptTcpClientAsync().ConfigureAwait(false); var s = new TcpClientEx(); s.AttachToSocket(ex.Client); //s.Client.SetupSocketTimeouts(new SocketSettings { NetworkClientKeepAliveInterval = 1000, NetworkClientKeepAliveTimeout = 1000 }); var remoteEndPoint = s.Client.RemoteEndPoint as IPEndPoint; if (remoteEndPoint != null) { logger.Trace($"Accepted a new client from {remoteEndPoint.Address}"); } logger.Notice($"Client connection accepted from {remoteEndPoint?.Address}:{remoteEndPoint?.Port}"); OnNewSocksClientConnected(s); } catch (Exception e) { logger.Error(e.Message); } } }); }
/// <summary> /// /// </summary> private void requestUserList() { #region TcpClientEx tcpclient = new TcpClientEx( ServerInfor._Ip.ToString(), Convert.ToInt16(ServerInfor._Port)); SendRequstFriendShip sendrequestfriendship = new SendRequstFriendShip() { _UserInfor = Logon._User }; byte[] command = sendrequestfriendship.GetProtocolCommand(); ExtConsole.WriteByteArray(command); tcpclient.Connect(); tcpclient.SendToEndDevice(command); tcpclient.ReceiveFile(); //RecvUserCheckResult usercheckresult = new RecvUserCheckResult(); //tcpclient.Dispatcher(usercheckresult); //Console.WriteLine(usercheckresult._Result._Message); tcpclient.Close(); #endregion }
public TcpBasicClientViewModel() { //1.the default spliter //IPacketSpliter spliter = new SimplePacketSpliter(); //2.packet with specific header which can prevent illegal network connection IPacketSpliter headerSpliter = new HeaderPacketSpliter(0xFFFF1111); //3.packet with length ahead in network byte order IPacketSpliter simpleSpliter = new SimplePacketSpliter(true); //4.packet end with specific mark IPacketSpliter endMarkSpliter = new EndMarkPacketSpliter(false, (byte)'\x04'); //5.packet that do not need to be split IPacketSpliter rawSpliter = RawPacketSpliter.Default; //6.custom packet spliter IPacketSpliter customSpliter = new CustomPacketSpliter(); //_tcpClient = new TcpClientEx(false); _tcpClient = new TcpClientEx(false, simpleSpliter); _tcpClient.ClientStatusChanged += OnTcpCient_ClientStatusChanged; _tcpClient.MessageReceived += OnTcpClient_PacketReceived; ClientSendText = "I am client"; }
public bool UserLogonRequest() { #region TcpClientEx tcpclient = new TcpClientEx( ServerInfor._Ip.ToString(), Convert.ToInt16(ServerInfor._Port)); SendUserValidCheck senduservalidcheck = new SendUserValidCheck() { _UserInfor = _User }; byte[] command = senduservalidcheck.GetProtocolCommand(); tcpclient.Connect(); tcpclient.SendToEndDevice(command); tcpclient.Receive(); RecvUserCheckResult usercheckresult = new RecvUserCheckResult(); tcpclient.Dispatcher(usercheckresult); tcpclient.Close(); if (usercheckresult._Result._Success) { string message = usercheckresult._Result._Message; int splitindex = message.IndexOf("-"); _User.uid = message.Substring(0, splitindex); _User.userfullName = message.Substring(splitindex + 1, message.Length - splitindex - 1); } return(usercheckresult._Result._Success); #endregion }
protected virtual Task OnClientConnected(TcpClientEx tcpClient) { if (ClientConnectedCallback != null) { return(ClientConnectedCallback(tcpClient)); } return(Task.CompletedTask); }
public Session(TcpClientEx client) { m_GamePack = new GamePackEx(); m_SocketState = SocketState.INIT; m_Client = client; m_Encrypt = new Encrypt(); m_Actor = new Actor(this); }
private async void btnConnection_Click(object sender, EventArgs e) { if (connectionStatus != Utility.ConnectionStatus.Connected) { string ip, port; IPAddress ipAddress; TcpClientEx tcpClient; connectionList = new ConcurrentBag <ClientRowInfo>(); for (int i = 0; i < gvList.Rows.Count - 1; i++) { gvList.Rows[i].Cells["Status"].Value = ParallelTcpClientConnectionApp.Properties.Resources.disconnected; ip = gvList.Rows[i].Cells["Ip"].Value?.ToString(); port = gvList.Rows[i].Cells["Port"].Value?.ToString(); tcpClient = new TcpClientEx(i); tcpClient.OnDisconnect += TcpClient_OnDisconnect; tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); connectionList.Add(new ClientRowInfo(i, ip, port, tcpClient)); } connectionStatus = Utility.ConnectionStatus.Awaiting; btnConnection.Enabled = false; gvList.AllowUserToAddRows = false; gvList.AllowUserToDeleteRows = false; await Task.Factory.StartNew(() => Parallel.ForEach(connectionList, connectionInfo => { Connect(connectionInfo); }) ); connectionStatus = Utility.ConnectionStatus.Connected; btnConnection.Text = "Disconnect"; btnConnection.Enabled = true; } else { connectionStatus = Utility.ConnectionStatus.Awaiting; btnConnection.Enabled = false; await Task.Factory.StartNew(() => Parallel.ForEach(connectionList, connectionInfo => { Disconnect(connectionInfo); }) ); connectionStatus = Utility.ConnectionStatus.Disconnected; btnConnection.Text = "Connect"; btnConnection.Enabled = true; gvList.AllowUserToAddRows = true; gvList.AllowUserToDeleteRows = true; } }
//public event EventHandler<ReceiveEventArgs> OnReceive = null; public static TcpClientEx ConnectServer() { #region TcpClientEx tcpclient = new TcpClientEx( ServerInfor._Ip.ToString(), Convert.ToInt16(ServerInfor._Port)); tcpclient.Connect(); return(tcpclient); #endregion }
private void _server_ClientStatusChanged(object sender, ClientStatusChangedEventArgs args) { if (!IsRunning) { return; } long proxyClientID = args.ClientID; if (args.Status == ClientStatus.Connected) { TcpClientEx tcpClient = new TcpClientEx(RawPacketSpliter.Default); tcpClient.Tag = proxyClientID; tcpClient.ClientStatusChanged += TcpClient_ClientStatusChanged; tcpClient.MessageReceived += TcpClient_MessageReceived; Task.Factory.StartNew(() => { bool isConnected = tcpClient.Connect(RemoteIP, (ushort)RemotePort); if (isConnected) { bool isOK = _clientDict.TryAdd(proxyClientID, tcpClient); System.Diagnostics.Debug.Assert(isOK, "add new client failed"); } else { _server.CloseClient(proxyClientID); } if (_waitConnDict.ContainsKey(proxyClientID)) { _waitConnDict[proxyClientID].Set(); } }); } else if (args.Status == ClientStatus.Closed) { if (_clientDict.TryRemove(proxyClientID, out TcpClientEx client)) { client.Close(); } } ClientCount = _server.Clients.Count; if (ClientCountChanged != null) { ClientCountChangedEventArgs countChangedArgs = new ClientCountChangedEventArgs() { NewCount = ClientCount }; ClientCountChanged(this, countChangedArgs); } }
public TcpClientEx ConnectTo(IPEndPoint connectTo) { var client = new TcpClientEx(); try { client.Connect(connectTo); } catch (SocketException) { throw new ConnectionEstablisherException(); } return(client); }
private void TcpClient_ClientStatusChanged(object sender, ClientStatusChangedEventArgs args) { if (!IsRunning) { return; } TcpClientEx clientEx = sender as TcpClientEx; long proxyClientID = (long)clientEx.Tag; if (args.Status == ClientStatus.Closed) { if (_clientDict.TryRemove(proxyClientID, out TcpClientEx client)) { _server.CloseClient(proxyClientID); } } }
private void btnStartSend_Click(object sender, EventArgs e) { MethodInvoker gd = new MethodInvoker(() => { TcpClientEx tcpclient = new TcpClientEx("192.168.159.104", 1005); SendFileSyn transfilesyn = new SendFileSyn(); tcpclient.Connect(); tcpclient.SendToEndDevice(transfilesyn.GetProtocolCommand()); tcpclient.Receive(); RecvFileAck transfileack = new RecvFileAck(); transfileack.OnStartingDownload += new EventHandler(StartingDownload); tcpclient.Dispatcher(transfileack); tcpclient.Close(); }); gd.BeginInvoke(null, null); }
private void TcpClient_MessageReceived(object sender, TcpRawMessageReceivedEventArgs args) { if (!IsRunning) { return; } TcpClientEx clientEx = sender as TcpClientEx; long proxyClientID = (long)clientEx.Tag; if (DataFilter != null) { DataFilter.BeforeServerToClient(new TcpRawMessage { ClientID = proxyClientID, MessageRawData = args.Message.MessageRawData }); } try { //the method may throw exception when stopping, so try catch is used but do nothing. _server.SendMessage(proxyClientID, args.Message.MessageRawData.ToArray()); } catch { } }
/// <summary> /// /// </summary> public void RegisterListen(IconController iconController) { #region TcpClientEx tcpclient = ChatClient.ConnectServer(); SendRegisterClientListen sendregister = new SendRegisterClientListen() { _UserInfor = Logon._User }; SendOnlineMarkup sendonlinemarkup = new SendOnlineMarkup() { _UserInfor = Logon._User }; byte[] sendregistercommand = sendregister.GetProtocolCommand(); byte[] sendonlinecommand = sendonlinemarkup.GetProtocolCommand(); tcpclient.SendToEndDevice(sendregistercommand); //可接收是否发送成功 while (true) { tcpclient.Receive(); switch (tcpclient.GetResolveType()) { case TProtocol.RecvChatContent: RecvChatContent chatcontentcmd = new RecvChatContent(); tcpclient.Dispatcher(chatcontentcmd); Friend friend = new Friend() { _User = new EntityTUser() { uid = chatcontentcmd._Content._FromUID.ToString() } }; int timestartindex = chatcontentcmd._Content._Text.Length - 19; string dt = chatcontentcmd._Content._Text.Substring(timestartindex, 19); ChatMessage message = new ChatMessage() { _Content = chatcontentcmd._Content._Text.Substring(0, timestartindex), _RecvTime = DateTime.Parse(dt) }; Friend findfriend = FriendCollector.FindFriend(friend); if (findfriend != null) { if (findfriend._MessageMode == MessageMode.HasPop) { findfriend._Messages.Add(message); TrafficMsg.PostMessage(int.Parse(findfriend._FrmHandle.ToString()), 500, 0, 0); } else { addMessageToFriend(findfriend, message); } } else { friend._User = UserMainWindow.GetFriendUser(friend._User.uid); friend._Messages = new List <ChatMessage>(); friend._MessageMode = MessageMode.None; friend._Messages.Add(message); FriendCollector.Add(friend); TrafficMsg.PostMessage(int.Parse(UserMainWindow._FrmHandle.ToString()), 501, 0, 0); } break; case TProtocol.RecvOnlineMarkup: tcpclient.SendToEndDevice(sendonlinecommand); break; } } #endregion }
/// <summary> /// Runs the client connection asynchronously. /// </summary> /// <returns>The task object representing the asynchronous operation.</returns> public async Task RunAsync() { ///尝试重新连接 bool isReconnected = true; int reconnectTry = -1; do { reconnectTry++; ByteBuffer = new ByteBuffer(); if (ServerTcpClient != null) { // Take accepted connection from listener tcpClient = ServerTcpClient; } else { // Try to connect to remote host var connectTimeout = TimeSpan.FromTicks(ConnectTimeout.Ticks + (MaxConnectTimeout.Ticks - ConnectTimeout.Ticks) / 20 * Math.Min(reconnectTry, 20)); tcpClient = new TcpClientEx(AddressFamily.InterNetwork); tcpClient.ReceiveTimeout = TcpPackConfig.ReceiveTimeout; tcpClient.SendTimeout = TcpPackConfig.SendTimeout; tcpClient.SendBufferSize = TcpPackConfig.SendBufferSize; tcpClient.ReceiveBufferSize = TcpPackConfig.ReceiveBufferSize; Message?.Invoke(this, new AsyncTcpEventArgs("准备连接到服务器" + IPAddress.ToString())); Task connectTask; if (!string.IsNullOrWhiteSpace(HostName)) { connectTask = tcpClient.ConnectAsync(HostName, Port); } else { connectTask = tcpClient.ConnectAsync(IPAddress, Port); } var timeoutTask = Task.Delay(connectTimeout); if (await Task.WhenAny(connectTask, timeoutTask) == timeoutTask) { //此处增加一个连接超时的任务 Message?.Invoke(this, new AsyncTcpEventArgs("连接超时")); OnConnectedTimeout(isReconnected);//连接超时的返回 continue; } try { await connectTask; } catch (Exception ex) { Message?.Invoke(this, new AsyncTcpEventArgs("连接到远程主机时出错", ex)); await timeoutTask; continue; } } reconnectTry = -1; stream = tcpClient.GetStream(); // 读取直到连接关闭。 //只有在读取时才能检测到闭合连接,因此我们需要读取 //永久地,不仅仅是当我们可能使用接收到的数据时。 var networkReadTask = Task.Run(async() => { // 10 KiB should be enough for every Ethernet packet byte[] buffer = new byte[TcpPackConfig.ByteBufferCapacity]; while (true) { int readLength; try { //异步读取有问题 readLength = await stream.ReadAsync(buffer, 0, buffer.Length); } catch (IOException ex) when((ex.InnerException as SocketException)?.ErrorCode == (int)SocketError.OperationAborted) { // Warning: This error code number (995) may change Message?.Invoke(this, new AsyncTcpEventArgs("本地关闭连接", ex)); readLength = -1; } catch (IOException ex) when((ex.InnerException as SocketException)?.ErrorCode == (int)SocketError.ConnectionAborted) { Message?.Invoke(this, new AsyncTcpEventArgs("连接失败", ex)); readLength = -1; } catch (IOException ex) when((ex.InnerException as SocketException)?.ErrorCode == (int)SocketError.ConnectionReset) { Message?.Invoke(this, new AsyncTcpEventArgs("远程重置连接", ex)); readLength = -2; } if (readLength <= 0) { if (readLength == 0) { Message?.Invoke(this, new AsyncTcpEventArgs("远程关闭连接")); } closedTcs.TrySetResult(true); OnClosed(readLength != -1); return; } //此处做处理,数据包要达到 var segment = new ArraySegment <byte>(buffer, 0, readLength); ByteBuffer.Enqueue(segment); await OnReceivedAsync(readLength); } }); closedTcs = new TaskCompletionSource <bool>(); await OnConnectedAsync(isReconnected); // Wait for closed connection await networkReadTask; tcpClient.Close(); isReconnected = true; }while (AutoReconnect && ServerTcpClient == null); }
public async Task RunAsync() { if (tcpListener != null) { if (TCPExceptionEvent != null) { TCPExceptionEvent(new InvalidOperationException("ERROR10029侦听器已在运行")); } return; } if (Port <= 0 || Port > ushort.MaxValue) { if (TCPExceptionEvent != null) { TCPExceptionEvent(new ArgumentOutOfRangeException(nameof(Port))); } return; } isStopped = false; closeClients = false; tcpListener = new TcpListener(IPAddress, Port); tcpListener.Start(); Message?.Invoke(this, new AsyncTcpEventArgs("等待连接")); clients = new ConcurrentDictionary <TcpClientEx, bool>(); // bool is dummy, never regarded var clientTasks = new List <Task>(); try { while (true) { TcpClient tc; TcpClientEx tcpClient = null;; try { tc = await tcpListener.AcceptTcpClientAsync(); tcpClient = new TcpClientEx(tc); tcpClient.ReceiveTimeout = TcpPackConfig.ReceiveTimeout; tcpClient.SendTimeout = TcpPackConfig.SendTimeout; tcpClient.SendBufferSize = TcpPackConfig.SendBufferSize; tcpClient.ReceiveBufferSize = TcpPackConfig.ReceiveBufferSize; } catch (ObjectDisposedException) when(isStopped) { // Listener was stopped break; } var endpoint = tcpClient.Client.RemoteEndPoint; Message?.Invoke(this, new AsyncTcpEventArgs("客户端连接来自 " + endpoint)); clients.TryAdd(tcpClient, true); var clientTask = Task.Run(async() => { await OnClientConnected(tcpClient); tcpClient.Dispose(); Message?.Invoke(this, new AsyncTcpEventArgs("与客户端连接 " + endpoint + "已经断开")); bool _value = false; clients.TryRemove(tcpClient, out _value); }); clientTasks.Add(clientTask); } } catch (Exception ex) { string str = ex.Message; } finally { if (closeClients) { Message?.Invoke(this, new AsyncTcpEventArgs("关闭,关闭所有客户端连接")); foreach (var tcpClient in clients.Keys) { tcpClient.Dispose(); } await Task.WhenAll(clientTasks); Message?.Invoke(this, new AsyncTcpEventArgs("已完成所有客户端连接")); } else { Message?.Invoke(this, new AsyncTcpEventArgs("关闭时,客户端连接保持打开状态")); } clientTasks.Clear(); tcpListener = null; } }