public void VoteUser(JObject jo, SocketConnection sConn) { var userName = jo["UserName"].ToString(); var voteUser = jo["VoteUser"].ToString(); if (!voteList.ContainsKey(userName)) { voteList.Add(userName, voteUser); } else { const string message = "ReviceVote|Flase|你已经投过票了,请不要重复投票!"; var dr = new DataFrame(message); sConn.ConnectionSocket.Send(dr.GetBytes()); return; } if (userList.Count != voteList.Count) return; var result = voteList.GroupBy(d => d.Value).Select( n => new { Count = n.Count(), value = n.FirstOrDefault().Value }).OrderByDescending(n => n.Count).ToList(); var voteTxt = voteList.Aggregate("", (current, vote) => current + (":" + vote.Key + ":" + vote.Value)); string resultVote = null; for (var i = 0; i < result.Count - 1; i++) { if (result[i].Count == result[i + 1].Count) { resultVote += "," + result[i + 1].value; } else { break; } } string style; string isOver; if (resultVote == null) { userList.Remove(result[0].value); resultVote = string.Format("{0}获得了{1}票,所以{0}出局!", result[0].value, result[0].Count); isOver = IsOver(result[0].value, userTitle[result[0].value]); style = "Kill"; } else { resultVote = string.Format("{0}等人票数相同,都是{1}票,所以进行PK!", result[0].value + resultVote, result[0].Count); style = "Pk"; isOver = "continue"; } voteList.Clear(); var msg = string.Format("ReviceVote|True|{0}|{1}|{2}|{3}|{4}|{5}", voteTxt, style, resultVote, result[0].value, userList[0], isOver); Send(msg); speak = userList[0]; if (isOver == "_over") { GameOver(); } }
public void SendTitle(JObject jo, SocketConnection sConn) { var userName = jo["UserName"].ToString(); string msg; if (titleList.Count == 0) { var requestPeople = jo["People"].ToString(); var requestGhost = jo["Ghost"].ToString(); var requestPeopleNum = Convert.ToInt32(jo["PeopleNum"].ToString()); var requestGhostNum = Convert.ToInt32(jo["GhostNum"].ToString()); var requestXiaoBai = Convert.ToInt32(jo["XiaoBai"].ToString()); titleUserName = userName; people = requestPeople; ghost = requestGhost; peopleNum = requestPeopleNum; ghostNum = requestGhostNum; for (var i = 0; i < requestPeopleNum; i++) { titleList.Add(requestPeople); } for (var i = 0; i < requestGhostNum; i++) { titleList.Add(requestGhost); } for (var i = 0; i < requestXiaoBai; i++) { titleList.Add("你是小白,伤不起"); } type = "_plan"; msg = string.Format("ReviceTitle|{0}已出题,请要参加的人员,赶快准备!|{0}", userName); Send(msg); } else { msg = string.Format("ReviceTitle|出题失败!{0}已出题,请先完成当前题目!!", titleUserName); var dr = new DataFrame(msg); sConn.ConnectionSocket.Send(dr.GetBytes()); } }
public void StartGame(JObject jo, SocketConnection sConn) { userList.Remove(sConn.Name); judge = sConn.Name; string msg; if (titleList.Count != userList.Count) { msg = string.Format("ReviceStartGame|False|抱歉,出题要求{0}人参加,但现在只有{1}人,所以游戏启动失败!", titleList.Count, userList.Count); Send(msg); } else { var num = Rank(); speak = userList[0]; var i = 0; foreach (var item in connectionSocketList) { if (item.Name != sConn.Name) { var title = titleList[num[i] - 1]; msg = string.Format("ReviceStartGame|True|游戏开始,{1}开始发言!|{0}|{1}", title, speak); if (!userTitle.ContainsKey(item.Name)) userTitle.Add(item.Name, title); i++; } else { type = "_game"; msg = string.Format("ReviceStartGame|True|游戏开始,{0}开始发言!|你是法官|{0}", speak); } var dr = new DataFrame(msg); item.ConnectionSocket.Send(dr.GetBytes()); } } }
public void Plan(JObject jo, SocketConnection sConn) { var user = jo["UserName"].ToString(); string msg; if (!userList.Contains(user)) { userList.Add(user); msg = string.Format("RevicePlan|True|{0}", user); Send(msg); } else { msg = string.Format("RevicePlan|False|你要爪子,准备了还点。。"); var dr = new DataFrame(msg); sConn.ConnectionSocket.Send(dr.GetBytes()); } }
// ReSharper restore FunctionNeverReturns public void SendUser(string message, SocketConnection item) { if (!item.ConnectionSocket.Connected) return; Logger.Log(Enums.LogType.Msg, message); try { if (item.IsDataMasked) { var dr = new DataFrame(message); item.ConnectionSocket.Send(dr.GetBytes()); } else { item.ConnectionSocket.Send(firstByte); item.ConnectionSocket.Send(Encoding.UTF8.GetBytes(message)); item.ConnectionSocket.Send(lastByte); } } catch (Exception ex) { Logger.Log(Enums.LogType.Error, ex.Message); } }
private void Read(IAsyncResult status) { if (!ConnectionSocket.Connected) return; var dr = new DataFrame(ReceivedDataBuffer); if (dr.OpCode == 10 || dr.OpCode == 9)//心跳检查 { ConnectionSocket.BeginReceive(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length, 0, Read, null); return; } try { string messageReceived; if (!isDataMasked) { // Web Socket protocol: messages are sent with 0x00 and 0xFF as padding bytes var decoder = new UTF8Encoding(); var startIndex = 0; // Search for the start byte while (ReceivedDataBuffer[startIndex] == firstByte[0]) startIndex++; // Search for the end byte var endIndex = startIndex + 1; while (ReceivedDataBuffer[endIndex] != lastByte[0] && endIndex != maxBufferSize - 1) endIndex++; if (endIndex == maxBufferSize - 1) endIndex = maxBufferSize; // Get the message messageReceived = decoder.GetString(ReceivedDataBuffer, startIndex, endIndex - startIndex); } else { messageReceived = dr.Text; } if ((messageReceived.Length == maxBufferSize && messageReceived[0] == Convert.ToChar(65533)) || messageReceived.Length == 0) { //Logger.Log("接受到的信息 [\"" + string.Format("logout:{0}",this.name) + "\"]"); if (Disconnected != null) Disconnected(this, EventArgs.Empty); return; } else { if (DataReceived != null) { //Logger.Log("接受到的信息 [\"" + messageReceived + "\"]"); DataReceived(this, messageReceived, EventArgs.Empty); } Array.Clear(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length); if (!ConnectionSocket.Connected) return; } ConnectionSocket.BeginReceive(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length, 0, Read, null); } catch (Exception ex) { var log = "----------------------------------------------------------------------------------" + "\r\n"; log += "错误信息:" + ex.Message+"\r\n"; log += "结果:该Socket连接将会被终止。" + "\r\n"; log += "----------------------------------------------------------------------------------" + "\r\n"; Logger.Log(Enums.LogType.Error, log); if (Disconnected != null) Disconnected(this, EventArgs.Empty); } }
public byte[] DataFramToBytes(DataFrame frame) { byte[] data = null; // TODO return data; }
public DataFrame Parse(byte[] dataFrame, bool toCopyData) { if (null == dataFrame) throw new WebsocketException("Data parse failed.") { ERRORCODE = WebsocketException.ERROR_CODE_ILLEGALARG }; DataFrame df = new DataFrame(); short curIdx; /* -------------- Parse 1st byte ---------------*/ curIdx = 0; df.IsFin = Convert.ToBoolean((byte)(0x80 & dataFrame[curIdx])); df.Rsv1 = (byte)(0x40 & dataFrame[curIdx]); df.Rsv2 = (byte)(0x20 & dataFrame[curIdx]); df.Rsv3 = (byte)(0x10 & dataFrame[curIdx]); df.OpCode = (OpCode)(0x0F & dataFrame[curIdx]); /* -------------- Parse 2nd byte ---------------*/ curIdx++; df.IsMasked = Convert.ToBoolean((byte)(0x80 & dataFrame[curIdx])); if (!df.IsMasked) throw new WebsocketException("The data are not masked") { ERRORCODE = WebsocketException.ERROR_CODE_ILLEGALSTATE }; int nextn = 0; Int64 len = (Int64)(0x8F & dataFrame[curIdx]); if (125 >= len) { df.DataLength = len; } else if (126 == len) { nextn = 2; } else { nextn = 8; } /* -------------- Parse payload lengh ---------------*/ if (nextn > 0) { for (int i = 0; i < nextn; i++) { curIdx++; len = len << 1; len = len | (0xFF & (uint)dataFrame[curIdx]); } df.DataLength = IPAddress.NetworkToHostOrder(len); // to local endian } /* -------------- Parse masking key ---------------*/ int maskkey = 0; for (int i = 0; i < 4; i++) { curIdx++; maskkey = maskkey << 1; maskkey = maskkey | (0xFF & dataFrame[curIdx]); } df.MaskingKey = maskkey; /* -------------- Parse payload data ---------------*/ if (toCopyData) { int offset = 0; df.Data = new byte[df.DataLength]; int round = (int)(df.DataLength / int.MaxValue); for (int i = 0; i <= round; i++) { int cnt; if (i == round) { cnt = (int)(df.DataLength % int.MaxValue); } else { cnt = int.MaxValue; } Buffer.BlockCopy(dataFrame, offset, df.Data, 0, cnt); offset += cnt; } df.DataOffset = 0; } else { df.Data = dataFrame; df.DataOffset = ++curIdx; } Unmask(df.Data, df.DataOffset, df.DataLength, df.MaskingKey); return df; }