A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 jerviscui 于 2013-6-24 19:57 编辑


今天在VS2010上做点练习,用Socket编程写的聊天程序。
长的比较丑


这是服务器的主要代码:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net.Sockets;
  10. using System.Net;
  11. using System.Threading;

  12. namespace _01_socketserver
  13. {
  14. public partial class SocketServer : Form
  15. {
  16. Socket socketWatch = null;
  17. delegate void SetTextCallback(string text);
  18. Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
  19. Thread receiveThread = null;

  20. public SocketServer()
  21. {
  22. InitializeComponent();
  23. }

  24. private void SocketServer_Load(object sender, EventArgs e)
  25. {
  26. //可以通过将 CheckForIllegalCrossThreadCalls 属性的值设置为 false 来禁用此异常
  27. //如果创建某控件的线程之外的其他线程试图调用该控件,则调试器会引发一个 InvalidOperationException
  28. //TextBox.CheckForIllegalCrossThreadCalls = false;

  29. //创建监听端口
  30. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  31. IPAddress adress = IPAddress.Parse(txtIP.Text.Trim());
  32. IPEndPoint endPoint = new IPEndPoint(adress, int.Parse(txtPort.Text.Trim()));
  33. //绑定端口
  34. socketWatch.Bind(endPoint);
  35. //设置监听队列
  36. socketWatch.Listen(10);
  37. ShowMsg("等待客户端连接...");

  38. //等待客户端连接
  39. //Socket connection = socketWatch.Accept();
  40. Thread thread = new Thread(new ThreadStart(WaitAccept));
  41. thread.IsBackground = true;
  42. thread.Start();

  43. }

  44. /// <summary>
  45. /// 显示文本信息
  46. /// </summary>
  47. /// <param name="msg"></param>
  48. private void ShowMsg(string msg)
  49. {
  50. if (txtShow.InvokeRequired)
  51. {

  52. SetTextCallback d = new SetTextCallback(ShowMsg); ;
  53. Invoke(d, new object[] { msg });
  54. }
  55. else
  56. {
  57. txtShow.AppendText(msg + "\r\n");
  58. }

  59. }

  60. /// <summary>
  61. /// 添加连接的客户端选项
  62. /// </summary>
  63. /// <param name="endpoint"></param>
  64. private void addEndPoint(string endpoint)
  65. {
  66. if (lbEndPoint.InvokeRequired)
  67. {
  68. SetTextCallback d = new SetTextCallback(addEndPoint);
  69. Invoke(d, new object[] { endpoint });
  70. }
  71. else
  72. lbEndPoint.Items.Add(endpoint);
  73. }

  74. /// <summary>
  75. /// 删除断开连接的客户端选项
  76. /// </summary>
  77. /// <param name="endpoint"></param>
  78. private void deleteEndPoint(int index)
  79. {
  80. if (lbEndPoint.InvokeRequired)
  81. {
  82. SetTextCallback d = new SetTextCallback(deleteEndPoint);
  83. Invoke(d, new object[] { index });
  84. }
  85. else
  86. lbEndPoint.Items.RemoveAt(index);
  87. }
  88. private void deleteEndPoint(string endpoint)
  89. {
  90. if (lbEndPoint.InvokeRequired)
  91. {
  92. SetTextCallback d = new SetTextCallback(deleteEndPoint);
  93. Invoke(d, new object[] { endpoint });
  94. }
  95. else
  96. lbEndPoint.Items.Remove(endpoint);
  97. }

  98. /// <summary>
  99. /// 等待连接线程函数
  100. /// </summary>
  101. private void WaitAccept()
  102. {
  103. while (true)
  104. {
  105. //等待客户端连接
  106. Socket connSocket = socketWatch.Accept();
  107. ShowMsg(connSocket.RemoteEndPoint.ToString() + "连接成功");
  108. //存储客户端列表
  109. dict.Add(connSocket.RemoteEndPoint.ToString(), connSocket);
  110. addEndPoint(connSocket.RemoteEndPoint.ToString());

  111. //接受线程启动
  112. receiveThread = new Thread(new ParameterizedThreadStart(ReceiveThread));
  113. receiveThread.IsBackground = true;
  114. receiveThread.Start((Object)connSocket.RemoteEndPoint.ToString());
  115. }

  116. }

  117. /// <summary>
  118. /// 接受数据线程方法
  119. /// </summary>
  120. /// <param name="obj"></param>
  121. private void ReceiveThread(Object obj)
  122. {
  123. while (true)
  124. {
  125. string endPoint = (string)obj;
  126. byte[] arrRec = new byte[1024 * 1024 * 2];
  127. int num = 0;
  128. try
  129. {
  130. num = dict[endPoint].Receive(arrRec);
  131. string strRec = dict[endPoint].RemoteEndPoint.ToString();
  132. strRec += ":" + System.Text.Encoding.Default.GetString(arrRec, 0, num);
  133. ShowMsg(strRec);
  134. }
  135. catch
  136. {
  137. ShowMsg(dict[endPoint].RemoteEndPoint.ToString() + "客户端关闭。");
  138. //关闭服务端套接字
  139. dict[endPoint].Close();
  140. //移除服务器列表项
  141. dict.Remove(endPoint);
  142. deleteEndPoint(endPoint);
  143. return;

  144. }

  145. }

  146. }

  147. /// <summary>
  148. /// 发送按钮
  149. /// </summary>
  150. /// <param name="sender"></param>
  151. /// <param name="e"></param>
  152. private void btnSend_Click(object sender, EventArgs e)
  153. {
  154. if (txtSend.Text.ToString() == "")
  155. {
  156. MessageBox.Show("发送内容不能为空!");
  157. }
  158. else
  159. {
  160. try
  161. {
  162. if (lbEndPoint.SelectedIndex == -1)
  163. lbEndPoint.SelectedIndex = 0;
  164. }
  165. catch
  166. {
  167. MessageBox.Show("没有可用的客户端");
  168. return;
  169. }
  170. //获取发送字符数组
  171. byte[] arrSend = System.Text.Encoding.Default.GetBytes(txtSend.Text.ToString());
  172. ShowMsg("to " + lbEndPoint.SelectedItem.ToString() + ":" + txtSend.Text.ToString());
  173. txtSend.Clear();
  174. try
  175. {
  176. //发送信息
  177. dict[lbEndPoint.SelectedItem.ToString()].Send(arrSend);
  178. }
  179. catch
  180. {
  181. ShowMsg("客户端已关闭。");
  182. //关闭服务端套接字
  183. dict[lbEndPoint.SelectedItem.ToString()].Close();
  184. //移除服务器列表项
  185. dict.Remove(lbEndPoint.SelectedItem.ToString());
  186. deleteEndPoint(lbEndPoint.SelectedIndex);
  187. }

  188. }//else

  189. }

  190. }
  191. }
复制代码

-The End-

© Jervis



评分

参与人数 1技术分 +1 收起 理由
杞文明 + 1

查看全部评分

1 个回复

倒序浏览
点发表之后我笑了  {:3_54:}

编辑的时候好好的,发出来就   :@:@

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马