先不给看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System.Net.Sockets; using System.Net; using System.Threading; namespace SocketServer { class Program { private static byte[] result = new byte[1024]; private static int myProt = 8885; //端口 static Socket serverSocket; static void Main(string[] args) { //服务器IP地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口 serverSocket.Listen(10); //设定最多10个排队连接请求 Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()); //通过Clientsoket发送数据 Thread myThread = new Thread(ListenClientConnect); myThread.Start(); Console.ReadLine(); } /// <summary> /// 监听客户端连接 /// </summary> private static void ListenClientConnect() { while (true) { Socket clientSocket = serverSocket.Accept(); clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello")); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); } } /// <summary> /// 接收消息 /// </summary> /// <param name="clientSocket"></param> private static void ReceiveMessage(object clientSocket) { Socket myClientSocket = (Socket)clientSocket; while (true) { try { //通过clientSocket接收数据 int receiveNumber = myClientSocket.Receive(result); Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)); } catch(Exception ex) { Console.WriteLine(ex.Message); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } } } } } |
Pingback引用通告: viagra online