CS监听模式ReceiveCallBack(IAsyncResult AR)

时间:2013-05-02 05:15:12
【文件属性】:

文件名称:CS监听模式ReceiveCallBack(IAsyncResult AR)

文件大小:155KB

文件格式:RAR

更新时间:2013-05-02 05:15:12

CS CS监听 客户端 服务器 客服

(注意使用前先将IP改为自己的IP或127.0.0.1) 本软件是使用套接字、ReceiveCallBack(IAsyncResult AR)函数为例的客服实例,修正了关闭客户端会导致异常的Bug;并且还是一个RichTextBox颜色使用的范例,不同的事件使用不同的颜色:如用户登录用红色、用户名用绿色、聊天内容用黑色^_^! 代码附赠全套注释,帮助初学者学习使用。 下面是核心代码 private void ReceiveCallBack(IAsyncResult AR) { try { DateTime dt = DateTime.Now; //如果服务器突然关闭后,客户端还坚持与之连接就会弹出异常; //检查是否套接字还连接上就可以避免这一问题。 if (!ClientSocket.Connected) { return; } //挂起AR,独占的使用AR来接收传过来的内容 int REnd = ClientSocket.EndReceive(AR); string StrOfREnd=Encoding.Unicode.GetString(MsgBuffer, 0, REnd); //截断的传输过来的字符串,"\n"前的是用户名 "\n"后的是聊天的内容 string UsersName = StrOfREnd.Substring(0, StrOfREnd.LastIndexOf("\n")); string Content = StrOfREnd.Substring(StrOfREnd.LastIndexOf("\n")+1); string Login=StrOfREnd.Substring(0,2); //MessageBox.Show("缓存中的内容:" + StrOfREnd + "\n" + "截断的用户名:" + UsersName + "\n" + "截断的内容:" + Content); if (Login != "登录") { //第一个字符不为“登陆” int oldlenth = tb_RecieveMsg.TextLength; this.tb_RecieveMsg.Select(oldlenth, 0); this.tb_RecieveMsg.SelectionColor = Color.Green; string str = Encoding.Unicode.GetString(MsgBuffer, 0, REnd); str = str.Substring(1, str.Length - 1); //用户使用绿色字体 this.tb_RecieveMsg.AppendText(" " + string.Format("{0:T}", dt) + " " + "用户:" + UsersName + "说:" + "\r\n"); this.tb_RecieveMsg.SelectionColor = Color.Black; this.tb_RecieveMsg.AppendText(" " + Content + "\r\n"); this.tb_RecieveMsg.AppendText("\r\n"); } else { //为登录时用红色字体 int oldlenth = tb_RecieveMsg.TextLength; this.tb_RecieveMsg.Select(oldlenth, 0); this.tb_RecieveMsg.SelectionColor = Color.Red; this.tb_RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd) + "\r\n"); this.tb_RecieveMsg.AppendText("\n"); this.tb_RecieveMsg.SelectionColor = Color.Black; } //放下AR,循环调用 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null); } catch (Exception ex) { MessageBox.Show(ex.Message); } }


【文件预览】:
CS监听模式
----TestServer()
--------TestServer.sln(920B)
--------_UpgradeReport_Files()
--------TestServer()
--------TestServer.suo(27KB)
--------UpgradeLog.XML(1KB)
----TestClient()
--------TestClient.sln(920B)
--------_UpgradeReport_Files()
--------TestClient()
--------UpgradeLog.XML(1KB)
--------TestClient.suo(23KB)

网友评论

  • 比较低级,没有什么用途
  • 好资源,谢谢分享。
  • 可以运行,分为客户端和服务器两个例子,但比较简单,和想象中的有所区别
  • 謝謝,用到了