//发送 public static void Send(ClientState cs, MsgChat msg) { //状态判断 if (cs == null) { return; } if (!cs.socket.Connected) { return; } //数据编码 byte[] nameBytes = MsgChat.EncodeName(msg); byte[] bodyBytes = MsgChat.Encode(msg); int len = nameBytes.Length + bodyBytes.Length; byte[] sendBytes = new byte[2 + len]; //组装长度 sendBytes[0] = (byte)(len % 256); sendBytes[1] = (byte)(len / 256); //组装名字 Array.Copy(nameBytes, 0, sendBytes, 2, nameBytes.Length); //组装消息体 Array.Copy(bodyBytes, 0, sendBytes, 2 + nameBytes.Length, bodyBytes.Length); //为简化代码,不设置回调 try { cs.socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, null, null); } catch (SocketException ex) { Console.WriteLine("Socket Close on BeginSend" + ex.ToString()); } }
public void SendChatMessage(ChatChannel channel, string text, string name, int?entityId) { MsgChat message = MakeNetChatMessage(channel, text, name, entityId); switch (channel) { case ChatChannel.Server: case ChatChannel.OOC: case ChatChannel.Radio: case ChatChannel.Player: case ChatChannel.Default: IoCManager.Resolve <IServerNetManager>().ServerSendToAll(message); break; case ChatChannel.Damage: case ChatChannel.Ingame: case ChatChannel.Visual: case ChatChannel.Emote: SendToPlayersInRange(message, entityId); break; case ChatChannel.Lobby: SendToLobby(message); break; } }
protected override void OnChatMessage(MsgChat msg) { //using (var a = new FileStream("Test.txt", FileMode.Append, FileAccess.Write)) //using (var b = new StreamWriter(a)) //{ // b.WriteLine($"{DateTime.Now.TimeOfDay}: OnChatMessage Called {msg.CarId}"); //} }
//发送MsgChat协议 public void OnChatClick() { MsgChat msg = new MsgChat(); msg.userName = myName.text; msg.chatMessage = myMessage.text; NetManager.Send(msg); }
//解码 public static MsgChat Decode(string protoName, byte[] bytes, int offset, int count) { string s = System.Text.Encoding.UTF8.GetString(bytes, offset, count); Newtonsoft.Json.Linq.JObject obj = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(s); MsgChat msgBase = obj.ToObject <MsgChat>(); return(msgBase); }
public void ProcessMsgChat(MsgChat msg, BasePlayer[] players) { string addText = "\n " + "<color=red>" + players[msg.id].username + "</color>: " + msg.chatmsg; chatText.text = chatText.text + addText; chatInput.ActivateInputField(); Canvas.ForceUpdateCanvases(); //关键代码 scrollRect.verticalNormalizedPosition = 0f; //关键代码 Canvas.ForceUpdateCanvases(); //关键代码 }
public static void MsgChat(ClientState c, MsgChat msgBase) { MsgChat msgChat = (MsgChat)msgBase; Console.WriteLine("接收到" + msgChat.userName + "用户消息" + msgChat.chatMessage); foreach (ClientState clientState in NetManager.clients.Values) { NetManager.Send(clientState, msgChat); } msgData.Add(msgChat); }
public UIScrollIndex AddItem(MsgChat msg) { UIScrollIndex item = CreateItem(mesNum); _content.GetComponent <RectTransform>().anchoredPosition = GetContentPos(); _content.GetComponent <RectTransform>().sizeDelta = GetContentSize(); item.mesIndex.text = mesNum.ToString(); item.mesText.text = DateTime.Now.ToLongTimeString().ToString() + msg.userName + ":" + msg.chatMessage; _mesText.Add(item.mesText.text); mesNum++; return(item); }
//数据处理 public static void OnReceiveData(ClientState state) { ByteArray readBuff = state.readBuff; //消息长度 if (readBuff.length <= 2) { return; } Int16 bodyLength = readBuff.ReadInt16(); //消息体 if (readBuff.length < bodyLength) { return; } //解析协议名 int nameCount = 0; string protoName = MsgChat.DecodeName(readBuff.bytes, readBuff.readIdx, out nameCount); if (protoName == "") { Console.WriteLine("OnReceiveData MsgBase.DecodeName fail"); Close(state); return; } readBuff.readIdx += nameCount; //解析协议体 int bodyCount = bodyLength - nameCount; MsgChat msgBase = MsgChat.Decode(protoName, readBuff.bytes, readBuff.readIdx, bodyCount); readBuff.readIdx += bodyCount; readBuff.CheckAndMoveBytes(); //分发消息 MethodInfo mi = typeof(MsgHandler).GetMethod(protoName); object[] o = { state, msgBase }; Console.WriteLine("Receive " + protoName); if (mi != null) { mi.Invoke(null, o); } else { Console.WriteLine("OnReceiveData Invoke fail " + protoName); } //继续读取消息 if (readBuff.length > 2) { OnReceiveData(state); } }
public void readMessage() { while (true) { MsgChat reciv = (MsgChat)Net.rcvMsg(comm.GetStream()); if (reciv.Topic == this.topic) { Console.WriteLine(reciv); } else if (reciv.Topic == this.pseudo) { Console.WriteLine("[" + reciv.Pseudo + "->" + reciv.Topic + "] : " + reciv); } } }
/// <summary> /// 发送发牌协议 /// </summary> /// <param name="client_id"></param> public void Update(int client_id) { //这个应该放在gameManager中,用于发送聊天的输入框 if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { if (chatInput.text != "") {//发送聊天协议 MsgChat msg = new MsgChat(); msg.chatmsg = chatInput.text; msg.id = client_id; chatInput.text = ""; NetManager.Send(msg); } } }
//编码协议名(2字节长度+字符串) public static byte[] EncodeName(MsgChat msgBase) { //名字bytes和长度 byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(msgBase.protoName); Int16 len = (Int16)nameBytes.Length; //申请bytes数值 byte[] bytes = new byte[2 + len]; //组装2字节的长度信息 bytes[0] = (byte)(len % 256); bytes[1] = (byte)(len / 256); //组装名字bytes Array.Copy(nameBytes, 0, bytes, 2, len); return(bytes); }
public static void MsgSyn(ClientState c, MsgChat msgSyn) { if (msgData.Count > 50) { for (int i = 0; i < 50; i++) { NetManager.Send(c, msgData[(msgData.Count - 1 - i)]); } Console.WriteLine("消息已同步到客户端"); } else { for (int i = 0; i < msgData.Count; i++) { NetManager.Send(c, msgData[i]); } Console.WriteLine("消息已同步到客户端"); } }
private void HandleChatMsg(MsgChat msg) { Logger.Debug($"Got it! {msg.Text}"); var channel = msg.Channel; var text = msg.Text; var index = msg.SessionId; var entityId = msg.EntityId; switch (channel) { case ChatChannel.Local: case ChatChannel.Server: case ChatChannel.OOC: case ChatChannel.Radio: { string name; if (index.HasValue && _players.SessionsDict.TryGetValue(index.Value, out var session)) { name = session.Name; } else if (entityId.HasValue) { var ent = _entityManager.GetEntity(entityId.Value); name = ent.Name ?? ent.ToString(); } else { name = "<TERU-SAMA>"; } text = $"[{channel}] {name}: {text}"; break; } } AddLine(text, channel, GetChannelColor(channel)); if (entityId.HasValue && _entityManager.TryGetEntity(entityId.Value, out var a)) { a.SendMessage(null, new SaidSomethingMsg(channel, text)); } }
public void sending() { //Connexion bool connect = false; while (!connect) { Account a = (Account)Net.rcvMsg(comm.GetStream()); foreach (Account account in Accounts) { if (account.Pseudo == a.Pseudo) { if (account.Password == a.Password) { connect = true; break; } } } if (connect) { Net.sendMsg(this.comm.GetStream(), new VerifAccount(true)); } else { Net.sendMsg(this.comm.GetStream(), new VerifAccount(false)); } } //Envoi des messages while (true) { MsgChat msg = (MsgChat)Net.rcvMsg(comm.GetStream()); Console.WriteLine(msg); Net.sendMsg(tcpClients, msg); } }
private MsgChat MakeNetChatMessage(ChatChannel channel, string text, string name, int?entityId) { string fullmsg = text; if (!string.IsNullOrEmpty(name) && channel == ChatChannel.Emote) { fullmsg = text; //Emote already has name in it probably... } else if (channel == ChatChannel.Ingame || channel == ChatChannel.OOC || channel == ChatChannel.Radio || channel == ChatChannel.Lobby) { fullmsg = name + ": " + text; } MsgChat message = IoCManager.Resolve <IServerNetManager>().CreateNetMessage <MsgChat>(); message.Channel = channel; message.Text = fullmsg; message.EntityId = entityId; return(message); }
public void HandleNetMessage(MsgChat message) { var channel = message.Channel; string text = message.Text; var client = message.MsgChannel; var session = IoCManager.Resolve <IPlayerManager>().GetSessionByChannel(message.MsgChannel); var playerName = session.Name; Logger.Debug("CHAT:: Channel: {0} :: Player: {1} :: Message: {2}", channel, playerName, text); var entityId = IoCManager.Resolve <IPlayerManager>().GetSessionById(message.MsgChannel.NetworkId).AttachedEntityUid; bool hasChannelIdentifier = false; if (channel != ChatChannel.Lobby) { channel = DetectChannel(text, out hasChannelIdentifier); } if (hasChannelIdentifier) { text = text.Substring(1); } text = text.Trim(); // Remove whitespace if (text[0] == '/') { ProcessCommand(text, playerName, channel, entityId, client); } else if (text[0] == '*') { ProcessEmote(text, playerName, channel, entityId, message.MsgChannel); } else { SendChatMessage(channel, text, playerName, entityId); } }
/// <summary> /// 服务端接收到协议,直接广播至这个房间内的所有玩家即可 /// </summary> /// <param name="msgBase"></param> public static void MsgChat(ClientState c, MsgBase msgBase) { MsgChat msg = (MsgChat)msgBase; Player player = c.player; if (player == null) { return; } Room room = RoomManager.GetRoom(player.roomId); if (room == null) { return; } GameManager gameManager = room.gameManager; if (gameManager == null) { return; } gameManager.Broadcast(msg); }
public void OnMsgSyn(MsgBase msgBase) { MsgChat msg = (MsgChat)msgBase; MessageShow(msg); }
protected override void OnChatMessage(MsgChat msg) { base.OnChatMessage(msg); Console.WriteLine("CHAT_" + msg.CarId + ": " + msg.Message); }
protected internal virtual void OnChatMessage(MsgChat msg) { }
public ChatMessage(AcDriverLeaderboardDetails author, MsgChat msg) { Author = author; Message = msg.Message; }
public void SendPrivateMessage(INetChannel client, ChatChannel channel, string text, string name, int?entityId) { MsgChat message = MakeNetChatMessage(channel, text, name, entityId); IoCManager.Resolve <IServerNetManager>().ServerSendMessage(message, client); }
//编码器 //static JavaScriptSerializer Js = new JavaScriptSerializer(); //编码 public static byte[] Encode(MsgChat msgBase) { string s = JsonConvert.SerializeObject(msgBase, Newtonsoft.Json.Formatting.Indented); return(System.Text.Encoding.UTF8.GetBytes(s)); }
public virtual void OnChatMessage(MsgChat msg) { }
protected override void OnChatMessage(MsgChat msg) { if (!msg.IsCommand) { return; } var split = msg.Message.Split(' '); if (split.Length > 0) { switch (split[0].ToLower()) { case "/mr": case "/minorating": { if (split.Length == 1) // only /mr { MRBackend.RequestDriverRatingAsync(msg.CarId); } else { MRBackend.RequestMRCommandAdminInfoAsync(msg.CarId, PluginManager.GetDriverInfo(msg.CarId).IsAdmin, split); } } break; case "/mrpoint": { string text; DriverInfo driver = null; if (!PluginManager.TryGetDriverInfo(Convert.ToByte(msg.CarId), out driver)) { text = "Driver not found: " + msg.CarId; } else if (driver?.LastCarUpdate?.Value == null) { text = "Something's wrong"; } else { var upd = driver?.LastCarUpdate?.Value; text = $"Spl:{upd.NormalizedSplinePosition:F5}|X={upd.WorldPosition.X:F5}|Z={upd.WorldPosition.Z:F5}"; } PluginManager.SendChatMessage(msg.CarId, text); } break; case "/mrinfo": { PluginManager.SendChatMessage(msg.CarId, $"Track id: {CurrentTrackDefinition?.TrackName}, length ={CurrentTrackDefinition?.Length:N0}"); PluginManager.SendChatMessage(msg.CarId, $"Pit exit: {PitExitRectangle?.X}"); } break; case "/mrtrackreload": { CurrentTrackDefinition = MRBackend.GetTrackDefinition(CurrentTrackDefinition.TrackName); CreatePitExitRectangle(); PluginManager.SendChatMessage(msg.CarId, $"Track reloaded"); } break; case "/mrtl1": { string text; DriverInfo driver = null; if (!PluginManager.TryGetDriverInfo(Convert.ToByte(msg.CarId), out driver)) { text = "Driver not found: " + msg.CarId; } else if (driver?.LastCarUpdate?.Value == null) { text = "Something's wrong"; } else { _AdminAddTrackLineStart = driver?.LastCarUpdate?.Value; text = $"Start set: {_AdminAddTrackLineStart}"; } PluginManager.SendChatMessage(msg.CarId, text); } break; case "/mrtl2": { Console.WriteLine("TrackLine 2"); string text = null; int type = 2; // pit exit = 1, default is line = 2 DriverInfo driver = null; if (_AdminAddTrackLineStart == null) { text = "No start set"; } else if (!PluginManager.TryGetDriverInfo(Convert.ToByte(msg.CarId), out driver)) { text = "Driver not found: " + msg.CarId; } else if (driver?.LastCarUpdate?.Value == null) { text = "Something's wrong"; } else if (split.Length < 2 || string.IsNullOrEmpty(split[1])) { text = "No hint set"; } else { if (split.Length == 3) { type = int.Parse(split[2]); } try { var startPoint = _AdminAddTrackLineStart; var endPoint = driver?.LastCarUpdate?.Value; MRBackend.CreateTrackLine(msg.CarId, startPoint.NormalizedSplinePosition, endPoint.NormalizedSplinePosition, startPoint.WorldPosition.X, startPoint.WorldPosition.Z, endPoint.WorldPosition.X, endPoint.WorldPosition.Z, split[1], type); Console.WriteLine($"Message sent, type {type}"); ReloadTrackDefinition(); PluginManager.SendChatMessage(msg.CarId, "Track reloaded"); } catch (Exception ex) { Console.WriteLine($"Exception in TrackLine2: {ex.ToString()}"); } } if (!string.IsNullOrEmpty(text)) { PluginManager.SendChatMessage(msg.CarId, text); } } break; default: break; } } }
protected override void OnChatMessage(MsgChat msg) { base.OnChatMessage(msg); DriverInfo driver = null; if (this.PluginManager.TryGetDriverInfo(msg.CarId, out driver) && driver.IsAdmin) { if (msg.Message.StartsWith("/next_track", StringComparison.InvariantCultureIgnoreCase)) { this.NextTrackAsync(true); } else if (msg.Message.StartsWith("/change_track ")) { string track = msg.Message.Substring("/change_track ".Length).Trim(); int trackIndex; if (!int.TryParse(track, out trackIndex) || trackIndex < 0 || trackIndex > this.Sessions.Count - 1) { string layout = string.Empty; string[] parts = track.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { track = parts[0]; layout = parts[1]; } trackIndex = this.GetTrackIndex(track, layout); } if (trackIndex > -1) { ThreadPool.QueueUserWorkItem(o => this.ChangeTrack(trackIndex, true)); } else { this.PluginManager.SendChatMessage(msg.CarId, "Specified track is not in trackcycle"); } } else if (msg.Message.StartsWith("/queue_track ")) { string track = msg.Message.Substring("/queue_track ".Length).Trim(); int trackIndex; if (!int.TryParse(track, out trackIndex) || trackIndex < 0 || trackIndex > this.Sessions.Count - 1) { string layout = string.Empty; string[] parts = track.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { track = parts[0]; layout = parts[1]; } trackIndex = this.GetTrackIndex(track, layout); } if (trackIndex > -1) { this.votes = null; //disable voting this.PluginManager.SendChatMessage(msg.CarId, "Next track will be " + this.Sessions[trackIndex]); this.cycle = trackIndex - 1; if (this.cycle < 0) { this.cycle = this.Sessions.Count - 1; } } else { this.PluginManager.SendChatMessage(msg.CarId, "Specified track is not in trackcycle"); } } } if (msg.Message.Equals("/list_tracks", StringComparison.InvariantCultureIgnoreCase)) { for (int i = 0; i < this.Sessions.Count; i++) { this.PluginManager.SendChatMessage(msg.CarId, i + ": " + this.Sessions[i]); } } if (msg.Message.StartsWith("/vote_track ", StringComparison.InvariantCultureIgnoreCase)) { if (driver == null) { this.PluginManager.SendChatMessage(msg.CarId, "Sorry, you can't vote at this time, please try again later."); return; } if (this.votes == null) { this.PluginManager.SendChatMessage(msg.CarId, "The admin already specified the next track, please try again later."); return; } if (this.votedIds.Contains(driver.DriverGuid)) { this.PluginManager.SendChatMessage(msg.CarId, "You can only vote once."); return; } string track = msg.Message.Substring("/vote_track ".Length).Trim(); int trackIndex; if (!int.TryParse(track, out trackIndex) || trackIndex < 0 || trackIndex > this.Sessions.Count - 1) { string layout = string.Empty; string[] parts = track.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { track = parts[0]; layout = parts[1]; } trackIndex = this.GetTrackIndex(track, layout); } if (trackIndex > -1) { this.votedIds.Add(driver.DriverGuid); this.votes[trackIndex]++; this.PluginManager.SendChatMessage(msg.CarId, "Vote registered."); } else { this.PluginManager.SendChatMessage(msg.CarId, "Specified track is not in trackcycle"); } } }
private void MessageShow(MsgChat msg) { Scroller.AddItem(msg); }