//线程调用:初始化 作为TCP服务器的时候,的前期工作 void gsz_init_tongxu() { try { //1:创建socket m_gsz_tcp_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2:绑定IP和端口 m_gsz_tcp_Server.Bind(new IPEndPoint(IPAddress.Any, 6000)); //3:开始监听,等待客户端的链接 m_gsz_tcp_Server.Listen(100); gsz_rizhi_meijie.rizhineirong = "服务器已经打开:开始监听6000端口"; gsz_rizhi_meijie.chufa_rizhi = true; do { } while (true != gsz_rizhi_meijie.chufa_rizhi); //4 等待客户的链接 m_Gsz_client_socket = m_gsz_tcp_Server.Accept();//暂停当前的线程,直到有一个客户端链接过来,然后才可以执行下面的代码 gsz_rizhi_meijie.rizhineirong = "客户端已经链接上"; gsz_rizhi_meijie.chufa_rizhi = true; do { } while (true != gsz_rizhi_meijie.chufa_rizhi); //5:发送数据 string gsz_message = "TCP_server_on"; byte[] data = Encoding.UTF8.GetBytes(gsz_message);//对字符串做编码,得到一个字符串的字节数组 m_Gsz_client_socket.Send(data); gsz_rizhi_meijie.rizhineirong = "发生数据:TCP_server_on给客户端"; gsz_rizhi_meijie.chufa_rizhi = true; do { } while (true != gsz_rizhi_meijie.chufa_rizhi); } catch (Exception e) { Console.WriteLine("Thread aborted."); } }