TcpListener

作者:追风剑情 发布于:2015-10-12 13:59 分类:C#


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Net;
  8. using System.Net.Sockets;
  9.  
  10. namespace TestServer
  11. {
  12. class Program
  13. {
  14. static List<ServerPlayer> playerList = new List<ServerPlayer>();
  15.  
  16. static void Main(string[] args)
  17. {
  18. TcpListener server=null;
  19. try
  20. {
  21. Int32 port = 13000;
  22. IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  23.  
  24. server = new TcpListener(localAddr, port);
  25. server.Start();
  26.  
  27. Console.WriteLine("Server started");
  28.  
  29. while(true)
  30. {
  31. Console.Write("Waiting for a connection... ");
  32.  
  33. TcpClient client = server.AcceptTcpClient();
  34. Console.WriteLine("Connected!");
  35. playerList.Add( new ServerPlayer(client) );
  36.  
  37. ThreadPoolInfo();
  38. }
  39. }
  40. catch(SocketException e)
  41. {
  42. Console.WriteLine("SocketException: {0}", e);
  43. }
  44. finally
  45. {
  46. server.Stop();
  47. }
  48.  
  49. Console.WriteLine("\nHit enter to continue...");
  50. Console.Read();
  51. }
  52.  
  53. //显示线程池现状
  54. static void ThreadPoolInfo()
  55. {
  56. int a, b;
  57. ThreadPool.GetAvailableThreads(out a, out b);
  58. string message = string.Format("CurrentThreadId is : {0}\n" +
  59. "WorkerThreads is : {1}\nCompletionPortThreads is : {2}\n",
  60. Thread.CurrentThread.ManagedThreadId, a.ToString(), b.ToString());
  61.  
  62. Console.WriteLine(message);
  63. }
  64. }
  65. }
  66.  
  67. public class ServerPlayer
  68. {
  69. private TcpClient tcpClient;
  70. private byte[] receiveBuffer;
  71. private string clientEndPoint;
  72.  
  73. public ServerPlayer(TcpClient tcpClient)
  74. {
  75. this.tcpClient = tcpClient;
  76. receiveBuffer = new byte[tcpClient.ReceiveBufferSize];
  77. //显示客户端信息
  78. clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
  79. Console.WriteLine("Client connected : " + clientEndPoint);
  80.  
  81. NetworkStream stream = tcpClient.GetStream();
  82. stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, new AsyncCallback(ReadCallback), stream);
  83. }
  84.  
  85. void ReadCallback(IAsyncResult result)
  86. {
  87. NetworkStream stream = (NetworkStream)result.AsyncState;
  88. int length = stream.EndRead(result);
  89. if (length < 1)//TCP中断了
  90. {
  91. Console.WriteLine("client disconnected : " + clientEndPoint);
  92. return;
  93. }
  94.  
  95. //显示接收信息
  96. string message = Encoding.UTF8.GetString(receiveBuffer, 0, length);
  97. Console.WriteLine("Message: " + message);
  98.  
  99. //向客户端返回ok
  100. byte[] msg = System.Text.Encoding.UTF8.GetBytes("ok");
  101. stream.Write(msg, 0, msg.Length);
  102.  
  103. stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, new AsyncCallback(ReadCallback), stream);
  104. }
  105. }


运行效果

tttt.png

示例二:增加大厅功能,实现聊天室

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Threading;
  7. using System.Net;
  8. using System.Net.Sockets;
  9.  
  10. namespace TestServer
  11. {
  12. class Program
  13. {
  14. static ServerLobby defaultLobby;
  15.  
  16. static void Main(string[] args)
  17. {
  18. TcpListener server = null;
  19. try
  20. {
  21. Int32 port = 13000;
  22. IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  23.  
  24. server = new TcpListener(localAddr, port);
  25. server.Start();
  26.  
  27. Console.WriteLine("Server started");
  28.  
  29. //建立默认大厅
  30. defaultLobby = new ServerLobby();
  31.  
  32. while (true)
  33. {
  34. Console.WriteLine("Waiting for a connection... ");
  35.  
  36. TcpClient client = server.AcceptTcpClient();
  37. Console.WriteLine("Connected!");
  38.  
  39. //进入大厅
  40. ServerPlayer player = new ServerPlayer(client);
  41. defaultLobby.OnEnterServerPlayer(player);
  42.  
  43. ThreadPoolInfo();
  44. }
  45. }
  46. catch (SocketException e)
  47. {
  48. Console.WriteLine("SocketException: {0}", e);
  49. }
  50. finally
  51. {
  52. server.Stop();
  53. }
  54.  
  55. Console.WriteLine("\nHit enter to continue...");
  56. Console.Read();
  57. }
  58.  
  59. //显示线程池现状
  60. static void ThreadPoolInfo()
  61. {
  62. int a, b;
  63. ThreadPool.GetAvailableThreads(out a, out b);
  64. string message = string.Format("CurrentThreadId is : {0}\n" +
  65. "WorkerThreads is : {1}\nCompletionPortThreads is : {2}\n",
  66. Thread.CurrentThread.ManagedThreadId, a.ToString(), b.ToString());
  67.  
  68. Console.WriteLine(message);
  69. }
  70. }
  71. }
  72.  
  73. // 大厅,管理所有ServerPlayer
  74. public class ServerLobby
  75. {
  76. private List<ServerPlayer> playerList = new List<ServerPlayer>();
  77.  
  78. // 有玩家进入大厅
  79. public void OnEnterServerPlayer(ServerPlayer player)
  80. {
  81. player.OnEnterLobby(this);
  82. playerList.Add(player);
  83. }
  84.  
  85. // 有玩家离开大厅
  86. public void OnLeaveServerPlayer(ServerPlayer player)
  87. {
  88. playerList.Remove(player);
  89. player.OnLeaveLobby();
  90. }
  91.  
  92. // 向大厅中的所有玩家广播消息
  93. public void BroadcastMessage(string msg)
  94. {
  95. for (int i=0; i<playerList.Count; i++)
  96. {
  97. if (playerList[i] == null)
  98. continue;
  99. playerList[i].SendMessage(msg);
  100. }
  101. }
  102. }
  103.  
  104. public class ServerPlayer
  105. {
  106. private TcpClient tcpClient;
  107. private NetworkStream stream;
  108. private byte[] receiveBuffer;
  109. private string clientEndPoint;
  110. private AsyncCallback mAsyncCallback;
  111. private ServerLobby mServerLobby;
  112. private string clientIP;
  113.  
  114. public string IP { get { return clientIP; } }
  115.  
  116. public ServerPlayer(TcpClient tcpClient)
  117. {
  118. this.tcpClient = tcpClient;
  119. receiveBuffer = new byte[tcpClient.ReceiveBufferSize];
  120. //显示客户端信息
  121. clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
  122. clientIP = clientEndPoint;
  123. Console.WriteLine("Client connected : " + clientEndPoint);
  124.  
  125. stream = tcpClient.GetStream();
  126. mAsyncCallback = new AsyncCallback(ReadCallback);
  127. stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, mAsyncCallback, stream);
  128. }
  129.  
  130. void ReadCallback(IAsyncResult result)
  131. {
  132. NetworkStream stream = (NetworkStream)result.AsyncState;
  133. int length = stream.EndRead(result);
  134. if (length < 1)//TCP中断了
  135. {
  136. Console.WriteLine("client disconnected : " + clientEndPoint);
  137. //离开大厅
  138. if (mServerLobby != null)
  139. mServerLobby.OnLeaveServerPlayer(this);
  140. return;
  141. }
  142.  
  143. //显示接收信息
  144. string message = Encoding.UTF8.GetString(receiveBuffer, 0, length);
  145. Console.WriteLine("Message: " + message);
  146.  
  147. //向大厅中的所有玩家同步消息
  148. mServerLobby.BroadcastMessage("sync: " + message.Trim() + "\r\n");
  149.  
  150. stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, mAsyncCallback, stream);
  151. }
  152.  
  153. // 发消息
  154. public void SendMessage(string msg)
  155. {
  156. if (!tcpClient.Connected)
  157. return;
  158.  
  159. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(msg);
  160. stream.Write(bytes, 0, msg.Length);
  161. }
  162.  
  163. // 本玩家进入大厅触发
  164. public void OnEnterLobby(ServerLobby lobby)
  165. {
  166. mServerLobby = lobby;
  167. //通知大厅中的其他玩家
  168. mServerLobby.BroadcastMessage(IP + " enter lobby\r\n");
  169. }
  170.  
  171. // 本玩家离开大厅触发
  172. public void OnLeaveLobby()
  173. {
  174. //通知大厅中的其他玩家
  175. mServerLobby.BroadcastMessage(IP + " leave lobby\r\n");
  176. mServerLobby = null;
  177. }
  178. }

运行测试

11111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号