static void Main(string[] args) { bool isRunningServer = true; Task.Factory.StartNew(() => { List<Client> clients=new List<Client>(); TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888); server.Start(); while (isRunningServer) { try { Client newClient=new Client(server.AcceptTcpClient()); clients.Add(newClient); newClient.Run(); } catch (Exception) { throw; } } },TaskCreationOptions.LongRunning); Console.WriteLine("running"); Console.ReadLine(); isRunningServer = false; Console.WriteLine("stoping"); Console.ReadLine(); }
//在新的线程中的操作,它主要用于当接收到一个客户端请求时,确认与客户端的连接, //并且立刻启动一个新的线程来处理和该客户端的信息交互。 private void StartSocketListen() { while (Form1.SocketServiceFlag) { try { //当接收到一个客户端请求时,确认与客户端的连接 if (listener.Pending())//检查是否连接请求,如果有则为True { Socket socket = listener.AcceptSocket(); if (clients.Count >= MAX_NUM) { //msg_Handle msg_Handle1 = new msg_Handle(this.rtbSocketMsg.AppendText); //this.rtbSocketMsg.Invoke(msg_Handle1, new object[]{"已经达到了最大连接数:" + // MAX_NUM + ",拒绝新的连接\n"}); ////this.rtbSocketMsg.AppendText("已经达到了最大连接数:" + //// MAX_NUM + ",拒绝新的连接\n"); socket.Close(); } else { //启动一个新的线程, //执行方法this.ServiceClient,处理用户相应的请求 Client client = new Client(this, socket); Thread clientService = new Thread( new ThreadStart(client.ServiceClient)); clientService.Start(); AutoRead(client); //client.ReadFromBuffer_ServerToOutside(); } } Thread.Sleep(200);//主线程休息200ms } catch (Exception ex) { msg_Handle msg_Handle2 = new msg_Handle(this.rtbSocketMsg.AppendText); this.rtbSocketMsg.Invoke(msg_Handle2, new object[] { ex.Message.ToString() + "\n" }); } } }
private void AutoRead(Client client) { timer1.Elapsed += (s_, e_) => client.ReadFromBuffer_ServerToOutside(); timer1.AutoReset = true; timer1.Enabled = true; }
private void SendToClient(Client client, string msg) { System.Byte[] message = System.Text.Encoding.Unicode.GetBytes( msg.ToCharArray()); client.CurrentSocket.Send(message, message.Length, 0); }
//SendToClient()方法实现了向客户端发送命令请求的功能 private void SendToClient(Client client, string command, string msg) { //string msg = System.Text.Encoding.Unicode.GetString(CreateFrame(command, msg)); byte[] message = CreateFrame(command, msg); client.CurrentSocket.Send(message, message.Length, 0); }