private void StreamRead(IAsyncResult ar) { try { int result = _stream.EndRead(ar); if (result > 0) { //_log.WriteLine($"Received {result} bytes !"); var cmd = Command.Parse(_buffer, 0, result); switch (cmd.CmdType) { case Command.CommandType.Ping: { SendCommand(new Command(Command.CommandType.Ping, new byte[] { 1 })); } break; case Command.CommandType.GetVersion: break; case Command.CommandType.CreateUser: { int errcode = BitConverter.ToInt32(cmd.Data); if (errcode == (int)CreateUserError.Success) { SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag))); } CreateUserCallBack?.Invoke(this, new CreateUserEventArgs((CreateUserError)errcode)); } break; case Command.CommandType.Message: { Message msg = Message.Parse(cmd.Data); MessageReceive?.Invoke(this, new MessageReceiveEventArgs(msg)); } break; case Command.CommandType.GetUserInfo: { User usr = User.Parse(cmd.Data); if (usr.Tag == CurrentUser.Tag) { this.usr = usr; } UserInfoReceive?.Invoke(this, new UserInfoReceiveEventArgs(usr)); } break; } } } catch (Exception ex) { _log.WriteLine(ex.ToString()); } _stream.BeginRead(_buffer, 0, _buffer.Length, StreamRead, ar.AsyncState); }
private void StreamRead(IAsyncResult ar) { try { int result = _stream.EndRead(ar); if (result > 0) { //_log.WriteLine($"Received {result} bytes !"); var cmd = Command.Parse(_buffer, 0, result); switch (cmd.CmdType) { case Command.CommandType.Ping: { SendCommand(new Command(Command.CommandType.Ping, new byte[] { 1 })); } break; case Command.CommandType.GetVersion: break; case Command.CommandType.CreateUser: { int errcode = BitConverter.ToInt32(cmd.Data); if (errcode == (int)CreateUserError.Success) { SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag))); } CreateUserCallBack?.Invoke(this, new CreateUserEventArgs((CreateUserError)errcode)); } break; case Command.CommandType.Message: { Message msg = Message.Parse(cmd.Data); MessageReceive?.Invoke(this, new MessageReceiveEventArgs(msg)); } break; case Command.CommandType.GetUserInfo: { User usr = User.Parse(cmd.Data); if (usr.Tag == CurrentUser.Tag) { this.usr = usr; } UserInfoReceive?.Invoke(this, new UserInfoReceiveEventArgs(usr)); } break; case Command.CommandType.ChangeUserPrivacy: { SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag))); } break; case Command.CommandType.LoginUser: { int errcode = BitConverter.ToInt32(cmd.Data, 0); if (errcode == (int)LoginUserError.Success) { byte[] tmp = new byte[cmd.Data.Length - 4]; Array.Copy(cmd.Data, 4, tmp, 0, tmp.Length); User usr = User.Parse(tmp); this.usr = usr; } LoginUserCallBack?.Invoke(this, new LoginUserEventArgs((LoginUserError)errcode)); } break; } } } catch (Exception ex) { _log.WriteLineError(ex); } try { if (!ar.CompletedSynchronously) { _stream.BeginRead(_buffer, 0, _buffer.Length, StreamRead, null); } } catch (Exception ex) { _log.WriteLineError(ex); } }