ChatServer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14. using Newtonsoft.Json;
  15. using SocketChat.Common;
  16. namespace SocketChat.Server
  17. {
  18. public partial class ChatServer : Form
  19. {
  20. #region 用户定义
  21. private List<Socket> _ClientProxSocketList = new List<Socket>();
  22. //连接的用户
  23. private List<User> userList = new List<User>();
  24. private List<OnlineUser> onlineUser = new List<OnlineUser>();
  25. private IPAddress localAddress;
  26. private int port = 51888;
  27. private delegate void SetListBoxCallBack(string str);
  28. private SetListBoxCallBack setListBoxCallback;
  29. private delegate void SetComboBoxCallBack(User user);
  30. private SetComboBoxCallBack setComboBoxCallback;
  31. private TcpListener myListener;
  32. private ArrayList MessList = new ArrayList();
  33. private int MessCount = 0;
  34. #endregion 用户定义
  35. #region 系统函数
  36. public ChatServer()
  37. {
  38. InitializeComponent();
  39. this.setListBoxCallback = new SetListBoxCallBack(SetListBox);
  40. this.setComboBoxCallback = new SetComboBoxCallBack(AddComboBoxItem);
  41. IPAddress[] addrIP = Dns.GetHostAddresses(this.txtIP.Text); //ip地址
  42. localAddress = addrIP[0];
  43. }
  44. #endregion 系统函数
  45. #region 用户函数
  46. public void fnConnection()
  47. {
  48. #region 另一种监听方式 已注释
  49. ////1.创建Socket对象
  50. //Socket __serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  51. ////2.绑定端口IP
  52. //IPAddress __ip = IPAddress.Parse(this.txtIP.Text);
  53. //__serverSocket.Bind(new IPEndPoint(__ip,int.Parse(this.txtPort.Text)));
  54. ////3.开始侦听
  55. ////连接等待的队列,最大为10个。
  56. ////如果同时来的100个连接请求,只能处理1个,队列中放着10个等待连接的客户端,其他的返回错误消息。
  57. //__serverSocket.Listen(100);
  58. ////4.开始接收客户端的连接
  59. //ThreadPool.QueueUserWorkItem(new WaitCallback(this.fnAcceptClientConnect), __serverSocket);
  60. #endregion 另一种监听方式 已注释
  61. myListener = new TcpListener(localAddress, int.Parse(this.txtPort.Text));
  62. myListener.Start();
  63. this.SetListBox(string.Format("开始在{0}:{1}监听客户连接", this.localAddress, this.port));
  64. //创建一个线程监听客户端连接请求
  65. ThreadStart ts = new ThreadStart(ListenClientConnect);
  66. Thread myThread = new Thread(ts);
  67. myThread.Start();
  68. btnStart.Enabled = false;
  69. btnStop.Enabled = true;
  70. }
  71. /// <summary>
  72. /// 接收客户端连接
  73. /// </summary>
  74. private void ListenClientConnect()
  75. {
  76. while (true)
  77. {
  78. TcpClient newClient = null;
  79. try
  80. {
  81. //等待用户进入
  82. newClient = myListener.AcceptTcpClient();
  83. }
  84. catch (Exception)
  85. {
  86. //当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常
  87. //因此可以利用此异常退出循环
  88. break;
  89. }
  90. //每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息
  91. ParameterizedThreadStart pts = new ParameterizedThreadStart(ReceiveData);
  92. Thread threadReceive = new Thread(pts);
  93. User user = new User(newClient);
  94. threadReceive.Start(user);
  95. userList.Add(user);
  96. AddComboBoxItem(user);
  97. SetListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint));
  98. SetListBox(string.Format("当前连接用户数:{0}", userList.Count));
  99. }
  100. }
  101. /// <summary>
  102. /// 接收、处理客户端信息,每客户1个线程,参数用于区分是哪个客户
  103. /// </summary>
  104. /// <param name="obj"></param>
  105. public void ReceiveData(object obj)
  106. {
  107. User user = obj as User;
  108. TcpClient client = user.client;
  109. //是否正常退出接收线程
  110. bool normalExit = false;
  111. //用于控制是否退出循环
  112. bool exitWhile = false;
  113. while (exitWhile == false)
  114. {
  115. string receiveString = null;
  116. try
  117. {
  118. //从网络流中读出字符串
  119. //此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
  120. receiveString = user.br.ReadString();
  121. }
  122. catch (Exception)
  123. {
  124. //底层套接字不存在时会出现异常
  125. SetListBox("接收数据失败");
  126. }
  127. if (receiveString == null)
  128. {
  129. if (normalExit == false)
  130. {
  131. //如果停止了监听,Connected为false
  132. if (client.Connected == true)
  133. {
  134. SetListBox(string.Format("与[{0}]失去联系,已终止接收该用户信息", client.Client.RemoteEndPoint));
  135. }
  136. }
  137. break;
  138. }
  139. SetListBox(string.Format("来自[{0}]:{1}", user.client.Client.RemoteEndPoint, receiveString));
  140. ClientMsgModel msg = new ClientMsgModel();
  141. msg = (ClientMsgModel)JsonConvert.DeserializeObject(receiveString, typeof(ClientMsgModel));
  142. switch (msg.Type)
  143. {
  144. case "1":
  145. this.SendLoginMsg(msg, user);
  146. break;
  147. case "2":
  148. User userReceive = this.userList.Where(delegate (User u)
  149. {
  150. return u.client.Client.RemoteEndPoint.ToString() == msg.ReceiveIP + ":" + msg.ReceivePort;
  151. }).FirstOrDefault();
  152. ServerMsgModel __serMsgModel = new ServerMsgModel();
  153. __serMsgModel.SendIP = (user.client.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
  154. __serMsgModel.SendPort = (user.client.Client.RemoteEndPoint as IPEndPoint).Port.ToString();
  155. __serMsgModel.SendUserName = msg.UserName;
  156. __serMsgModel.SendType = msg.Type;
  157. __serMsgModel.SendMsg = msg.Msg;
  158. string __sendSerMsg = JsonConvert.SerializeObject(__serMsgModel);
  159. SendToClient(userReceive, __sendSerMsg);
  160. break;
  161. default: break;
  162. }
  163. }
  164. userList.Remove(user);
  165. client.Close();
  166. SetListBox(string.Format("当前连接用户数:{0}", userList.Count));
  167. }
  168. private void SendTalkMsg()
  169. {
  170. }
  171. /// <summary>
  172. /// 服务器向客户端发消息
  173. /// </summary>
  174. /// <param name="msg">消息</param>
  175. /// <param name="user">客户端</param>
  176. public void SendLoginMsg(ClientMsgModel msg, User user)
  177. {
  178. //IPAddress ip = IPAddress.Parse(user.client.Client.RemoteEndPoint.ToString());
  179. OnlineUser __onlineUser = new OnlineUser();
  180. __onlineUser.IP = (user.client.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
  181. __onlineUser.Port = (user.client.Client.RemoteEndPoint as IPEndPoint).Port.ToString();
  182. __onlineUser.UserName = msg.UserName;
  183. if (!this.onlineUser.Contains(__onlineUser))
  184. {
  185. this.onlineUser.Add(__onlineUser);
  186. }
  187. SetListBox(string.Format("登录IP:{0},端口:{1}", msg.IP, msg.Port));
  188. ServerMsgModel __serMsgModel = new ServerMsgModel();
  189. __serMsgModel.SendIP = msg.IP;
  190. __serMsgModel.SendPort = msg.Port;
  191. __serMsgModel.SendUserName = msg.UserName;
  192. __serMsgModel.SendType = msg.Type;
  193. __serMsgModel.OnlineUser = this.onlineUser;
  194. string __sendSerMsg = JsonConvert.SerializeObject(__serMsgModel);
  195. for (int i = 0; i < this.userList.Count; i++)
  196. {
  197. SendToClient(userList[i], __sendSerMsg);
  198. }
  199. }
  200. public void SendToClient(User user, string str)
  201. {
  202. try
  203. {
  204. user.bw.Write(str);
  205. user.bw.Flush();
  206. SetListBox(string.Format("向[{0}]发送:{1}", user.client.Client.RemoteEndPoint, str));
  207. }
  208. catch
  209. {
  210. SetListBox(string.Format("向[{0}]发送信息失败", user.client.Client.RemoteEndPoint));
  211. }
  212. }
  213. private void SetListBox(string str)
  214. {
  215. if (this.listBoxStatus.InvokeRequired)
  216. {
  217. this.Invoke(this.setListBoxCallback, str);
  218. }
  219. else
  220. {
  221. this.listBoxStatus.AppendText(str + Environment.NewLine);
  222. }
  223. }
  224. private void AddComboBoxItem(User user)
  225. {
  226. if (this.comboBoxReceiver.InvokeRequired)
  227. {
  228. this.Invoke(setComboBoxCallback, user);
  229. }
  230. else
  231. {
  232. this.comboBoxReceiver.Items.Add(user.client.Client.RemoteEndPoint);
  233. }
  234. }
  235. #region 暂时不用
  236. /// <summary>
  237. /// 接收客户端连接 暂不用
  238. /// </summary>
  239. public void fnAcceptClientConnect(object v_socket)
  240. {
  241. var __serverSocket = v_socket as Socket;
  242. Server.SetListBox("服务器端开始接收客户端链接");
  243. while (true)
  244. {
  245. Socket __proxSocket = __serverSocket.Accept();
  246. Server.SetListBox(string.Format("客户端:{0}连接上了", __proxSocket.RemoteEndPoint.ToString()));
  247. this._ClientProxSocketList.Add(__proxSocket);
  248. //不停的接收当前链接的客户端发送来的消息
  249. ThreadPool.QueueUserWorkItem(new WaitCallback(this.fnReceiveData), __proxSocket);
  250. }
  251. }
  252. /// <summary>
  253. /// 接收客户端的消息
  254. /// </summary>
  255. /// <param name="v_socket"></param>
  256. public void fnReceiveData(object v_socket)
  257. {
  258. var __proxSocket = v_socket as Socket;
  259. byte[] data = new byte[1024 * 1024];
  260. while (true)
  261. {
  262. int __iLen = 0;
  263. try
  264. {
  265. __iLen = __proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
  266. }
  267. catch (Exception)
  268. {
  269. //异常退出
  270. Server.SetListBox(string.Format("客户端:{0}非正常退出",
  271. __proxSocket.RemoteEndPoint.ToString()));
  272. this._ClientProxSocketList.Remove(__proxSocket);
  273. this.fnStopConnect(__proxSocket);
  274. return;
  275. }
  276. if (__iLen <= 0)
  277. {
  278. //客户端正常退出
  279. Server.SetListBox(string.Format("客户端:{0}正常退出",
  280. __proxSocket.RemoteEndPoint.ToString()));
  281. this._ClientProxSocketList.Remove(__proxSocket);
  282. this.fnStopConnect(__proxSocket);//停止连接
  283. return;//让方法结束,终结当前接收客户端数据的异步线程。
  284. }
  285. }
  286. }
  287. private void fnStopConnect(Socket proxSocket)
  288. {
  289. try
  290. {
  291. if (proxSocket.Connected)
  292. {
  293. proxSocket.Shutdown(SocketShutdown.Both);
  294. proxSocket.Close(100);
  295. }
  296. }
  297. catch (Exception ex)
  298. {
  299. throw;
  300. }
  301. }
  302. private void StopServer()
  303. {
  304. try
  305. {
  306. SetListBox(string.Format("目前连接用户数:{0}", userList.Count));
  307. SetListBox("开始停止服务,并依次使用户退出!");
  308. for (int i = 0; i < userList.Count; i++)
  309. {
  310. comboBoxReceiver.Items.Remove(userList[i].client.Client.RemoteEndPoint);
  311. userList[i].br.Close();
  312. userList[i].bw.Close();
  313. userList[i].client.Close();
  314. }
  315. //通过停止监听让myListener.AcceptTcpClient()产生异常退出监听线程
  316. myListener.Stop();
  317. this.btnStart.Enabled = true;
  318. this.btnStop.Enabled = false;
  319. }
  320. catch (Exception ex)
  321. {
  322. throw ex;
  323. }
  324. }
  325. #endregion 暂时不用
  326. #endregion 用户函数
  327. #region 窗体事件
  328. private void buttonSend_Click(object sender, EventArgs e)
  329. {
  330. User clientUser = new User(new TcpClient());
  331. foreach (User u in userList)
  332. {
  333. if (u.client.Client.RemoteEndPoint.ToString() == comboBoxReceiver.SelectedText)
  334. {
  335. clientUser = u;
  336. }
  337. }
  338. if (clientUser != null)
  339. {
  340. SendToClient(clientUser, txtSendMsg.Text.Trim());
  341. }
  342. }
  343. private void ChatServer_FormClosing(object sender, FormClosingEventArgs e)
  344. {
  345. //关闭server线程
  346. StopServer();
  347. Application.Exit();
  348. }
  349. private void btnStart_Click(object sender, EventArgs e)
  350. {
  351. try
  352. {
  353. this.fnConnection();
  354. }
  355. catch (Exception ex)
  356. {
  357. throw ex;
  358. }
  359. }
  360. private void btnStop_Click(object sender, EventArgs e)
  361. {
  362. StopServer();
  363. }
  364. #endregion 窗体事件
  365. }
  366. }