// 处理接收的服务器收据 private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { MessageBox.Show("与服务器失去联系"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "login": //格式: login,用户名 AddOnline(splitString[1]); break; case "logout": //格式: logout,用户名 if (!receiveString.Contains("_")) { RemoveUserName(splitString[1]); } break; case "talk": //格式: talk,自己ID,对方ID,对话信息 message_Notifition(receiveString); break; case "response": //格式: response,自己会话ID //message_Notifition(receiveString); /*string talkString_response = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); * new Thread((ThreadStart)delegate * { * Application.Run(new chat_online(id, talkString_response, true)); * }).Start();*/ break; } } Thread.CurrentThread.Abort(); //Application.Exit(); }
private void ReceiveData(object userState) { TcpUser user = (TcpUser)userState; TcpClient client = user.client; while (!isExit) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { RemoveUser(user); } break; } AsyncSendToClient(user, receiveString); } }
/// <summary> /// 处理接收的服务器收据 /// </summary> private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(100); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { dgLog("与服务器失去联系,即将开始重新链接..."); IsConnect = false; } break; } //string[] splitString = receiveString.Split(','); //string command = splitString[0].ToLower(); try { RevMsg = Derializer(receiveString); if (RevMsg != null) { string str = "2&"; str += (int)RevMsg.Order + "&"; str += RevMsg.DataInfo; AddTalkMessage(str); } else { AddTalkMessage("消息解析失败:" + receiveString); } } catch (Exception ex) { AddTalkMessage("消息解析失败:" + receiveString); } } }
/// <summary> /// 处理接收的服务器端数据 /// </summary> private void ReceiveData() { string receiveString = null; while (isExit == false) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (result.IsCompleted == false) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (isExit == false) { MessageBox.Show("与服务器失去联系。"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "login": //格式:login,用户名 AddOnline(splitString[1]); break; case "logout": //格式:logout,用户名 RemoveUserName(splitString[1]); break; case "talk": //格式:talk,用户名,对话信息 AddTalkMessage(splitString[1] + ":\r\n"); AddTalkMessage(receiveString.Substring( splitString[0].Length + splitString[1].Length + 2)); break; } } Application.Exit(); }
private void ReceiveAccept() { while (true) { var client = new Client(); try { client.ClientSocket = _socket.Accept(); AddRunningInfo(">> " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " Client[" + client.ClientSocket.RemoteEndPoint + "] connected."); _receiveMessageDelegate = ReceiveMessages; _receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, ""); } catch (Exception ex) { throw new Exception(ex.Message); } } }
private void ReceiveAccept() { while (true) { Client client = new Client(); try { client.ClientSocket = m_serverSocket.Accept(); this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client[" + client.ClientSocket.RemoteEndPoint.ToString() + "] connected."); receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages); receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, ""); } catch (Exception ex) { // throw new Exception(ex.Message); MessageBox.Show(ex.Message); } } }
//<summary> //处理接收的客户端信息 //</summary> //<param name="userState">客户端信息</param> private void ReceiveData(object obj) { ClientUser user = (ClientUser)obj; TcpClient client = user.Client; while (user.IsNormalExit == false) { string receiveString = null; lock (objlock) { AddUser(user); ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receiveString, null, null); if (!result.IsCompleted) { d.EndInvoke(out receiveString, result); } } } }
/// <summary> /// 处理接收的服务器收据 /// </summary> private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { if (MessageBox.Show("与服务器失去联系") == DialogResult.OK) { connectWork.RunWorkerAsync();//重新连接 } } break; } // 接收到的数据处理 ReceiveMes(receiveString); } }
private void ReceiveData(object userState) { User user = (User)userState; TcpClient client = user.client; while (!isExit) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receiveString, null, null); //使用輪詢方式來判斷非同步作業是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //獲取Begin方法的返回值和所有輸入/輸出參數 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { AddItemToListBox(string.Format("與{0}失去聯繫,已終止接收該使用者資訊", client.Client.RemoteEndPoint)); RemoveUser(user); } break; } AddItemToListBox(string.Format("來自[{0}]:{1}", user.client.Client.RemoteEndPoint, receiveString)); string[] splitString = receiveString.Split(','); switch (splitString[0]) { case "Login": user.userName = splitString[1]; AsyncSendToAllClient(user, receiveString); break; case "Logout": AsyncSendToAllClient(user, receiveString); RemoveUser(user); return; case "Talk": //格式=代號,收信,訊息 string talkString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); AddItemToListBox(string.Format("{0}對{1}說:{2}", user.userName, splitString[1], talkString)); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "talk," + talkString); break; } } break; case "TalkOne": string talkOneString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "talkone," + talkOneString); break; } } break; case "FormatOne": string formOneString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "formatone," + formOneString); break; } } break; case "TalkAll": //格式= 代號,寄信,訊息 string talkAllString = receiveString.Substring(splitString[0].Length + 1); AddItemToListBox(string.Format("{0}說:{1}", user.userName, talkAllString)); AsyncSendToAllClient(user, "talkall," + talkAllString); break; case "Format": //格式=代號,收件,format string formString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "format," + formString); break; } } break; case "FormatAll": //格式=代號,format string formatAllString = receiveString.Substring(splitString[0].Length + 1); AsyncSendToAllClient(user, "formatall," + formatAllString); break; case "Start the game": user.userName = splitString[1]; AddItemToListBox2(string.Format("{0}", user.userName)); StartTheGame(); break; case "Leave the game": user.userName = splitString[1]; RemoveItemToListBox2(user.userName); AddItemToListBox(string.Format("{0} 退出遊戲", user.userName)); break; case "Playing": user.userName = splitString[1]; AddItemToListBox(string.Format("{0} 進行遊戲中...", user.userName)); break; case "Cancel": user.userName = splitString[1]; RemoveItemToListBox2(user.userName); break; case "turnto": string userinput = splitString[1]; if (listBox2.Items.Count <= 0) { string message = "GameisOver,"; for (int i = 0; i < userList.Count; i++) { AsyncSendToClient(userList[i], message); person = 0; } break; } else if (person < listBox2.Items.Count - 1) { this.person = person + 1; } else { this.person = 0; } round(userinput); break; case "Gameisover": Form.CheckForIllegalCrossThreadCalls = false; listBox2.Items.Clear(); string message2 = "GameisOver,"; for (int i = 0; i < userList.Count; i++) { AsyncSendToClient(userList[i], message2); } break; } } }
private void ReceiveData(object userState) { User user = (User)userState; TcpClient client = user.client; while (!isExit) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { AddItemToListBox(string.Format("与{0}失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint)); RemoveUser(user); } break; } AddItemToListBox(string.Format("来自[{0}]:{1}", user.client.Client.RemoteEndPoint, receiveString)); string[] splitString = receiveString.Split(','); switch (splitString[0]) { case "Login": user.userName = splitString[1]; AsyncSendToAllClient(user, receiveString); break; case "Logout": AsyncSendToAllClient(user, receiveString); RemoveUser(user); return; case "Talk": string talkString = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); AddItemToListBox(string.Format("{0}对{1}说:{2}", user.userName, splitString[1], talkString)); foreach (User target in userList) { if (target.userName == splitString[1]) { AsyncSendToClient(target, "talk," + user.userName + "," + talkString); break; } } break; default: AddItemToListBox("什么意思啊:" + receiveString); break; } } }
/// <summary> /// 处理接收的服务器收据 /// </summary> private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) break; Thread.Sleep(100); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { dgLog("与服务器失去联系,即将开始重新链接..."); IsConnect = false; } break; } //string[] splitString = receiveString.Split(','); //string command = splitString[0].ToLower(); try { RevMsg = Derializer(receiveString); if (RevMsg != null) { string str = "2&"; str += (int) RevMsg.Order + "&"; str += RevMsg.DataInfo; AddTalkMessage(str); } else { AddTalkMessage("消息解析失败:"+receiveString); } } catch (Exception ex) { AddTalkMessage("消息解析失败:"+receiveString); } } }
private void ReceiveData(object userState) { ServerInfo info = (ServerInfo)userState; TcpClient client = info.client; while (!isExit) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(info, out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (!result.IsCompleted) { if (isExit) break; Thread.Sleep(100); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { dgLog(string.Format("与{0} {1}失去联系,已终止接收该用户信息", info.Content.ClientName, client.Client.RemoteEndPoint)); dgRomoveCilent(info); } break; } //dgLog(string.Format("来自[{0}]:{1}", info.Content.ClientName, info.Content.DataInfo)); string[] splitString = receiveString.Split(','); switch (info.Content.Order) { case SocketOrder.Login: dgLog(string.Format("客户端{0}上线:{1}", info.Content.ClientName, info.client.Client.RemoteEndPoint)); dgAddClient(info); InfoList.Add(info); break; case SocketOrder.Logout: dgLog(string.Format("客户端{0}下线:{1}", info.Content.ClientName, info.client.Client.RemoteEndPoint)); dgRomoveCilent(info); InfoList.Remove(info); break; case SocketOrder.StartReg: AsyncSendToClient(info); break; case SocketOrder.RegSuccess: AsyncSendToClient(info); break; case SocketOrder.StartCckq: AsyncSendToClient(info); break; case SocketOrder.CckqSuccess: AsyncSendToClient(info); break; case SocketOrder.StartTckq: AsyncSendToClient(info); break; case SocketOrder.TckqSuccess: AsyncSendToClient(info); break; case SocketOrder.StartDown: AsyncSendToClient(info); break; case SocketOrder.DownSuccess: AsyncSendToClient(info); break; default: AsyncSendToClient(info); dgLog("未知命令[已转发]:" + info.Content.Order); break; } } }
private void ReceiveData(object userState) { ServerInfo info = (ServerInfo)userState; TcpClient client = info.client; while (!isExit) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(info, out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(100); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { dgLog(string.Format("与{0} {1}失去联系,已终止接收该用户信息", info.Content.ClientName, client.Client.RemoteEndPoint)); dgRomoveCilent(info); } break; } //dgLog(string.Format("来自[{0}]:{1}", info.Content.ClientName, info.Content.DataInfo)); string[] splitString = receiveString.Split(','); switch (info.Content.Order) { case SocketOrder.Login: dgLog(string.Format("客户端{0}上线:{1}", info.Content.ClientName, info.client.Client.RemoteEndPoint)); dgAddClient(info); InfoList.Add(info); break; case SocketOrder.Logout: dgLog(string.Format("客户端{0}下线:{1}", info.Content.ClientName, info.client.Client.RemoteEndPoint)); dgRomoveCilent(info); InfoList.Remove(info); break; case SocketOrder.StartReg: AsyncSendToClient(info); break; case SocketOrder.RegSuccess: AsyncSendToClient(info); break; case SocketOrder.StartCckq: AsyncSendToClient(info); break; case SocketOrder.CckqSuccess: AsyncSendToClient(info); break; case SocketOrder.StartTckq: AsyncSendToClient(info); break; case SocketOrder.TckqSuccess: AsyncSendToClient(info); break; case SocketOrder.StartDown: AsyncSendToClient(info); break; case SocketOrder.DownSuccess: AsyncSendToClient(info); break; default: AsyncSendToClient(info); dgLog("未知命令[已转发]:" + info.Content.Order); break; } } }
/// <summary> /// 处理接收的服务器收据 /// </summary> private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { MessageBox.Show("与服务器失去联系"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0]; switch (command) { case "Login": //格式: login,用户名 for (int i = 0; i < userInfo.Length; i++) { if (userInfo[i, 0] != null) { continue; } else { userInfo[i, 0] = splitString[1].Substring(245); userInfo[i, 1] = splitString[1]; AddOnline(userInfo[i, 0]); //MessageBox.Show("dan yonghuming: "+userInfo[i, 0] + "\n wanzhengmingzi: " + userInfo[i, 1]); break; //rtf_SendMessage.Text = userInfo[i, 0] + "\n" + userInfo[i, 1]; } } //AddOnline(splitString[1]); break; case "Logout": //格式: logout,用户名 RemoveUserName(splitString[1].Substring(245)); break; case "Talk": //格式: talk,用户名,对话信息 AddTalkMessage(splitString[1].Substring(245) + " to " + txt_UserName.Text + ":\r\n"); string finalmessage = SRSA.Decrypt(splitString[2]); AddTalkMessage(finalmessage + "\n"); //AddTalkMessage(receiveString.Substring(splitString[0].Length + splitString[1].Length + 2)); break; } } Application.Exit(); }
// 处理接收的服务器收据 private void ReceiveData() { if (isLogin) { AsyncSendMessage("Login_server," + UserID + "," + Password); } else { AsyncSendMessage("Regdit_server," + UserID + "," + UserName + "," + Password + "," + cls); } string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { MessageBox.Show("与服务器失去联系"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); isRec = true; switch (command) { case "suc": //格式: login,用户名 flag = true; if (isLogin) { Settings.Default.NAME = splitString[2]; } //MessageBox.Show(splitString[1]+splitString[2]); else { MessageBox.Show(splitString[1]); } isExit = true; break; case "error": //格式: logout,用户名 flag = false; MessageBox.Show(splitString[1] + splitString[2]); isExit = true; break; } } Read.Close(); Write.Close(); client.Close(); Thread.CurrentThread.Abort(); }
/// <summary> /// 接收、处理客户端信息,每客户1个线程,参数用于区分是哪个客户 /// </summary> /// <param name="obj">客户端</param> private void ReceiveData(object obj) { User user = (User)obj; TcpClient client = user.client; while (isExit == false) { string receiveString = null; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (result.IsCompleted == false) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if(receiveString==null) { if (isExit == false) { service.AddItem(string.Format("与[{0}]失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint)); RemoveClientfromPlayer(user); } break; } service.AddItem(string.Format("来自{0}:{1}", user.userName, receiveString)); string[] splitString = receiveString.Split(','); int tableIndex = -1; //桌号 int side = -1; //座位号 int anotherSide = -1; //对方座位号 string sendString = ""; string command = splitString[0].ToLower(); switch (command) { case "login": //格式:Login,昵称 //该用户刚刚登录 if (userList.Count > maxUsers) { sendString = "Sorry"; service.AsyncSendToOne(user, sendString); service.AddItem("人数已满,拒绝" + splitString[1] + "进入游戏室"); RemoveClientfromPlayer(user); } else { //将用户昵称保存到用户列表中 //由于是引用类型,因此直接给user赋值也就是给userList中对 //应的user赋值 //用户名中包含其IP和端口的目的是为了帮助理解,实际游戏 //中一般不会显示IP的 user.userName = string.Format("[{0}--{1}]", splitString[1], client.Client.RemoteEndPoint); //允许该用户进入游戏室,即将各桌是否有人情况发送给该用户 sendString = "Tables," + this.GetOnlineString(); service.AsyncSendToOne(user, sendString); } break; case "logout": //格式:Logout //用户退出游戏室 service.AddItem(string.Format("{0}退出游戏室", user.userName)); RemoveClientfromPlayer(user); return; case "sitdown": //格式:SitDown,桌号,座位号 //该用户坐到某座位上 tableIndex = int.Parse(splitString[1]); side = int.Parse(splitString[2]); gameTable[tableIndex].gamePlayer[side].user = user; gameTable[tableIndex].gamePlayer[side].someone = true; service.AddItem(string.Format( "{0}在第{1}桌第{2}座入座", user.userName, tableIndex + 1, side + 1)); //得到对家座位号 anotherSide = (side + 1) % 2; //判断对方是否有人 if (gameTable[tableIndex].gamePlayer[anotherSide].someone == true) { //先告诉该用户对家已经入座 //发送格式:SitDown,座位号,用户名 sendString = string.Format("SitDown,{0},{1}", anotherSide, gameTable[tableIndex].gamePlayer[anotherSide].user.userName); service.AsyncSendToOne(user, sendString); } //同时告诉两个用户该用户入座(也可能对方无人) //发送格式:SitDown,座位号,用户名 sendString = string.Format("SitDown,{0},{1}", side, user.userName); service.SendToBoth(gameTable[tableIndex], sendString); //重新将游戏室各桌情况发送给所有用户 service.SendToAll(userList, "Tables," + this.GetOnlineString()); break; case "getup": //格式:GetUp,桌号,座位号 //用户离开座位,回到游戏室 tableIndex = int.Parse(splitString[1]); side = int.Parse(splitString[2]); service.AddItem( string.Format("{0}离座,返回游戏室", user.userName)); gameTable[tableIndex].StopTimer(); //将离座信息同时发送给两个用户,以便客户端作离座处理 //发送格式:GetUp,座位号,用户名 service.SendToBoth(gameTable[tableIndex], string.Format("GetUp,{0},{1}", side, user.userName)); //服务器进行离座处理 gameTable[tableIndex].gamePlayer[side].someone = false; gameTable[tableIndex].gamePlayer[side].started = false; gameTable[tableIndex].gamePlayer[side].grade = 0; anotherSide = (side + 1) % 2; if (gameTable[tableIndex].gamePlayer[anotherSide].someone == true) { gameTable[tableIndex].gamePlayer[anotherSide].started = false; gameTable[tableIndex].gamePlayer[anotherSide].grade = 0; } //重新将游戏室各桌情况发送给所有用户 service.SendToAll(userList, "Tables," + this.GetOnlineString()); break; case "level": //格式:Time,桌号,难度级别 //设置难度级别 tableIndex = int.Parse(splitString[1]); gameTable[tableIndex].SetTimerLevel((6 - int.Parse(splitString[2])) * 100); service.SendToBoth(gameTable[tableIndex], receiveString); break; case "talk": //格式:Talk,桌号,对话内容 tableIndex = int.Parse(splitString[1]); //由于说话内容可能包含逗号,所以需要特殊处理 sendString = string.Format("Talk,{0},{1}", user.userName, receiveString.Substring(splitString[0].Length + splitString[1].Length)); service.SendToBoth(gameTable[tableIndex], sendString); break; case "start": //格式:Start,桌号,座位号 //该用户单击了开始按钮 tableIndex = int.Parse(splitString[1]); side = int.Parse(splitString[2]); gameTable[tableIndex].gamePlayer[side].started = true; if (side == 0) { anotherSide = 1; sendString = "Message,黑方已开始。"; } else { anotherSide = 0; sendString = "Message,白方已开始。"; } service.SendToBoth(gameTable[tableIndex], sendString); if (gameTable[tableIndex].gamePlayer[anotherSide].started == true) { gameTable[tableIndex].ResetGrid(); //gameTable[tableIndex].StartTimer(); gameTable[tableIndex].Turn = 0; } break; case "unsetdot": //格式:UnsetDot,桌号,座位号,行,列,颜色 //消去客户单击的棋子 tableIndex = int.Parse(splitString[1]); side = int.Parse(splitString[2]); int xi = int.Parse(splitString[3]); int xj = int.Parse(splitString[4]); int color = int.Parse(splitString[5]); gameTable[tableIndex].UnsetDot(xi, xj, color); break; case "setdot"://edit tableIndex = int.Parse(splitString[1]); side = int.Parse(splitString[2]); int xit = int.Parse(splitString[3]); int xjt = int.Parse(splitString[4]); int colort = int.Parse(splitString[5]); gameTable[tableIndex].SetDot(xit, xjt, colort); break; default: service.SendToAll(userList, "什么意思啊:" + receiveString); break; } } userList.Remove(user); client.Close(); service.AddItem(string.Format("有一个退出,剩余连接用户数:{0}", userList.Count)); }
private void ReceiveData(object userState) { User user = (User)userState; TcpClient client = user.client; while (!Instance.ISExit) { string receive = string.Empty; ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(user, out receive, null, null); //使用轮询方式来判断异步操作是否完成 while (!result.IsCompleted) { if (Instance.ISExit) { break; } Thread.Sleep(50); //Thread.Sleep(100); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receive, result); if (receive.Length == 0 || receive == null) { if (!Instance.ISExit) { //日志 Console.WriteLine(string.Format("与{0}失去联系,已终止接收该用户信息", user.IP)); RemoveUser(user); } break; } string aswer = string.Empty; CommandManage manage = new CommandManage(); try { Console.WriteLine("接受:" + receive); aswer = manage.Proc(receive); Console.WriteLine("应答:" + aswer); } catch { manage.CloseUser = true; } //foreach (User target in Instance.UserList) //{ // if (target.IP == client.Client.RemoteEndPoint.ToString()) // { // AsyncSendToClient(target, aswer); // } //} AsyncSendToClient(user, aswer); if (manage.CloseUser) { this.RemoveUser(user); } } }
// 处理接收的服务器收据 private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来盘点异步操作是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值所有输入/输出参数 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { MessageBox.Show("与服务器失去联系"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "login": //格式: login,用户名 break; case "logout": //格式: logout,用户名 if (splitString[1].Equals(aim_id_temp) || splitString[1].Equals(aim_id)) { isExit = true; //做一个委托; } break; case "talk": //格式: talk,用户名,对话信息 AddTalkMessage(id_name[splitString[1].Split('_')[0]] + ":\r\n"); AddTalkMessage(receiveString.Substring(splitString[0].Length + splitString[1].Length + 2)); break; /*case "response"://格式: response,自己会话ID * AsyncSendMessage("_response," + id); * break;*/ case "_response": // _response,对方会话ID isCat = true; string talkString_response_ = receiveString.Substring(splitString[0].Length + splitString[1].Length + 2); SetTextInputEnable(true); aim_id = talkString_response_; break; case "NoFound": isCat = false; aim_id = aim_id.Split('_')[0]; break; case "?": AsyncSendMessage("!," + aim_id + "," + id); break; case "!": isCat = true; isRece = false; break; } } Thread.CurrentThread.Abort(); File.Delete(Application.StartupPath + "\\temp_" + aim_id + ".bin"); }
/// <summary>处理接收数据</summary> private void ReceiveData() { string receiveString = null; while (isExit == false) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(ReceiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用轮询方式来判断异步操作是否完成 while (result.IsCompleted == false) { if (isExit) { break; } Thread.Sleep(250); } //获取Begin方法的返回值和所有输入/输出参数 d.EndInvoke(out receiveString, result); if(receiveString==null) { if (isExit == false) { MessageBox.Show("与服务器失去联系,游戏无法继续!"); } if (side != -1) { ExitFormPlaying(); } side = -1; isExit = true; //结束线程 break; } service.AddItemToListBox("收到:" + receiveString); string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "sorry": MessageBox.Show("连接成功,但游戏室人数已满,无法进入。"); break; case "tables": //字符串格式:Tables,各桌是否有人的字符串 //其中每位表示一个座位,1表示有人,0表示无人 string s = splitString[1]; //如果maxPlayingTables为0,说明尚未创建checkBoxGameTables if (maxPlayingTables == 0) { //计算所开桌数 maxPlayingTables = s.Length / 2; checkBoxGameTables = new CheckBox[maxPlayingTables, 2]; isReceiveCommand = true; //将CheckBox对象添加到数组中,以便管理 for (int i = 0; i < maxPlayingTables; i++) { AddCheckBoxToPanel(s, i); } isReceiveCommand = false; } else { isReceiveCommand = true; for (int i = 0; i < maxPlayingTables; i++) { for (int j = 0; j < 2; j++) { if (s[2 * i + j] == '0') { UpdateCheckBox(checkBoxGameTables[i, j], false); } else { UpdateCheckBox(checkBoxGameTables[i, j], true); } } } isReceiveCommand = false; } break; case "sitdown": //格式:SitDown,座位号,用户名 formPlaying.SetTableSideText(splitString[1], splitString[2], string.Format("{0}进入", splitString[2])); break; case "getup": //格式:GetUp,座位号,用户名 //自己或者对方离座 if (side == int.Parse(splitString[1])) { //自己离座 side = -1; } else { //对方离座 formPlaying.SetTableSideText(splitString[1], "", string.Format("{0}退出", splitString[2])); formPlaying.Restart("敌人逃跑了,我方胜利了"); } break; case "lost": //格式:Lost,座位号,用户名 //对家与服务器失去联系 formPlaying.SetTableSideText(splitString[1], "", string.Format("[{0}]与服务器失去联系", splitString[2])); formPlaying.Restart("对家与服务器失去联系,游戏无法继续"); break; case "talk": //格式:Talk,说话者,对话内容 if (formPlaying != null) { //由于说话内容可能包含逗号,所以需要特殊处理 formPlaying.ShowTalk(splitString[1], receiveString.Substring(splitString[0].Length + splitString[1].Length + splitString[2].Length + 3)); } break; case "message": //格式:Message,内容 //服务器自动发送的一般信息(比如进入游戏桌入座等) formPlaying.ShowMessage(splitString[1]); break; case "level": //设置难度级别 //格式:Time,桌号,难度级别 formPlaying.SetLevel(splitString[2]); break; case "setdot": //产生的棋子位置信息 //格式:Setdot,行,列,颜色 formPlaying.SetDot( int.Parse(splitString[1]), int.Parse(splitString[2]), (DotColor)int.Parse(splitString[3])); break; case "unsetdot": //消去棋子的信息 //格式:UnsetDot,行,列,黑方成绩,白方成绩 int x = 20 * (int.Parse(splitString[1]) + 1); int y = 20 * (int.Parse(splitString[2]) + 1); formPlaying.UnsetDot(x, y); formPlaying.SetGradeText(splitString[3], splitString[4]); break; case "win": //格式:Win,相邻棋子的颜色,黑方成绩,白方成绩 string winner = ""; if ((DotColor)int.Parse(splitString[1]) == DotColor.Black) { winner = "黑方出现五子相连,黑方胜利!";//edit } else { winner = "白方出现五子相连,白方胜利!";//edit } formPlaying.ShowMessage(winner); formPlaying.Restart(winner); break; } } //接收线程结束后,游戏继续进行已经没有意义,所以直接退出程序 Application.Exit(); }
/// <summary> /// 處理接收的伺服器收據 /// </summary> private void ReceiveData() { string receiveString = null; while (!isExit) { ReceiveMessageDelegate d = new ReceiveMessageDelegate(receiveMessage); IAsyncResult result = d.BeginInvoke(out receiveString, null, null); //使用輪詢方式來盤點非同步作業是否完成 while (!result.IsCompleted) { if (isExit) { break; } Thread.Sleep(250); } //獲取Begin方法的返回值所有輸入/輸出參數 d.EndInvoke(out receiveString, result); if (receiveString == null) { if (!isExit) { MessageBox.Show("與伺服器失去聯繫"); } break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "login": //格式: login,用戶名 AddOnline(splitString[1]); break; case "logout": //格式: logout,用戶名 RemoveUserName(splitString[1]); break; case "talk": //格式: talk,用戶名,對話資訊 AddTalkMessage(receiveString.Substring(splitString[0].Length + 1)); break; case "talkone": if (CR == null) { CR = new ChattingRom(); CR.AddTalkMessage(splitString[1] + splitString[2]); CR.SetText(splitString[1]); CR.talker = splitString[1]; CR.chatting += new Chatting(chatting); Application.Run(CR); } else { CR.rtf_MessageInfo.AppendText(splitString[1] + splitString[2]); CR.AddTalkMessage(splitString[1] + splitString[2]); CR.chatting += new Chatting(chatting); // Application.Run(CR); } // break; case "talkall": //格式: talkAll,計件者,資訊 AddTalkMessage(receiveString.Substring(splitString[0].Length + splitString[1].Length + 2)); break; case "formatone": CR.SetFont(receiveString); break; case "format": case "formatall": SetFont(receiveString); break; case "allready": gameisOpen = true; button3.Enabled = false; killMessageBox(); break; case "startgame": if (splitString[4] == "true") { max = int.Parse(splitString[2]); min = int.Parse(splitString[3]); } else { max = 100; min = 0; } Game a = new Game(splitString[1], min.ToString(), max.ToString(), textBox1.Text); a.finish += new CheckFinish(checkfinish); a.leave += new CancelGame(cancelGame); Application.Run(a); break; case "gameisover": Form.CheckForIllegalCrossThreadCalls = false; button2.Enabled = true; button3.Enabled = true; button4.Enabled = false; break; } } if (isExit == true) { MessageBox.Show("登出成功"); } Application.Exit(); }