public void Send(Client client, byte[] data, int dataSize) { ClientEx clientEx = client as ClientEx; if (clientEx == null) { return; } if (clientEx.TokenSource.Token.IsCancellationRequested) { return; } if (clientEx.Client.Connected == false) { return; } int offset = 0, encrytpSize = 0;; while (dataSize > 0) { encrytpSize = dataSize > StandardBuffLenMax ? StandardBuffLenMax : dataSize; byte[] sendData; int sendSize = this._encrytper.EncrytpData(clientEx.PubKey, data, offset, encrytpSize, out sendData); clientEx.Stream.WriteAsync(sendData, 0, sendSize, clientEx.TokenSource.Token); clientEx.Stream.FlushAsync(clientEx.TokenSource.Token); offset += encrytpSize; dataSize -= encrytpSize; } }
private bool StopListenClient(ClientEx client) { client.TokenSource.Cancel(); if (false == client.Task.Wait(1000)) { this.PushErrorEvent(client, $"Failed to Stop listen client {client.IP}::{client.Port}"); return(false); } return(true); }
public bool StartServe(string ip, int port) { if (this._server != null) { this.PushErrorEvent(null, "You must STOP serve before START."); return(false); } bool result = false; this._server = new TCPServer(); this._server._syncEvent = new AutoResetEvent(false); this._server._serveTask = new Task(async() => { try { IPAddress address; if (false == IPAddress.TryParse(ip, out address)) { address = IPAddress.Any; } using (this._encrytper = new Encrytper()) { // this._server._listener = new TcpListener(address, port); this._server._listener.Start(); //打开成功,设置信号 this._server._serveFlag = true; this._clientList = new List <ClientEx>(); result = true; this._server._syncEvent.Set(); //监测新Client while (this._server._serveFlag) { if (_server._listener.Pending()) { var c = await _server._listener.AcceptTcpClientAsync(); if (c != null) { ClientEx client = new ClientEx(c); this.StartListenClient(client); } } else { await Task.Delay(10); } } //该关闭服务了 this._server._listener.Stop(); while (this._clientList.Count() > 0) { this.StopListenClient(this._clientList.First()); } } } catch (Exception ex) { //异常 this.PushErrorEvent(null, ex.Message); } finally { var syncEvent = this._server._syncEvent; this._server = null; syncEvent.Set(); syncEvent.Dispose(); } }, TaskCreationOptions.LongRunning); this._server._serveTask.Start(); //等待结果 this._server?._syncEvent.WaitOne(1500); return(result); }
private void MissClient(ClientEx client) { _clientList.Remove(client); MissClientEvent?.Invoke(this, client); }
private void PushNewClient(ClientEx client) { _clientList.Add(client); AcceptClientEvent?.Invoke(this, client); }
private void PostLoseConnection(ClientEx client) => LoseConnectionEvent?.Invoke(this, client);
private bool StartListenClient(ClientEx client) { var signal = new ManualResetEventSlim(false); client.Task = Task.Run(async() => { //第一个try catch被认为,无法连接成功 try { using (client.Client) using (client.Stream = client.Client.GetStream()) using (client.TokenSource.Token.Register(() => client.Stream.Close())) { var stream = client.Stream; //Send key await stream.WriteAsync(this._encrytper.CrypPubKey, 0 , this._encrytper.CrypPubKey.Length, client.TokenSource.Token); await stream.FlushAsync(client.TokenSource.Token); //Wait for key byte[] readBuff = new byte[StandardBuffLen]; int readSize = await stream.ReadAsync(readBuff, 0, readBuff.Length, client.TokenSource.Token); if (readSize != this._encrytper.CrypPubKey.Length) { throw new Exception("Failed to exchange key."); } client.PubKey = new byte[readSize]; Array.Copy(readBuff, client.PubKey, readSize); try { //连接成功的信号 signal.Set(); //上报 PushNewClient(client); while (client.TokenSource.Token.IsCancellationRequested == false && readSize > 0) { readSize = await stream.ReadAsync(readBuff, 0, readBuff.Length, client.TokenSource.Token); if (readSize > 0) { byte[] data; int dataSize = this._encrytper.DecrytpData(client.PubKey, readBuff, 0, readSize, out data); Message msgEx = new Message(client, data, ref dataSize); this.PushMessageEvent(msgEx); } } } catch (Exception ex) { ex.GetType(); } finally { //任何异常,都被视为连接成功后,断开连接。 //上报掉线 MissClient(client); } } } catch (ObjectDisposedException ex) { ex.GetType(); } catch (Exception ex) { this.PushErrorEvent(client, ex.Message); } finally { signal.Set(); signal.Dispose(); } }); if (signal.Wait(3000)) { return(true); } //等待不到,就自动关闭 client.TokenSource.Cancel(); return(false); }
private void ServerFound(object sender, ClientEx args) { }