public class TestConnect { string hostIp = ""; int port = 3314; public string recMsg = ""; Socket socketC = null; private readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false); public TestConnect(string hostIp, int port) { this.hostIp = hostIp; this.port = port; } public bool connect() { ///創建終結點(EndPoint) IPAddress ip = IPAddress.Parse(hostIp);//把ip地址字符串轉換為IPAddress類型的實例 IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint類的新實例 ///創建socket socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建一個socket對像,如果用udp協議,則要用SocketType.Dgram類型的套接字 try { return Connect(ipe,3000); } catch (SocketException ex) { socketC.Close(); socketC = null; return false; } } /// <summary> /// Socket連接請求 /// </summary> /// <param name="remoteEndPoint">網絡端點</param> /// <param name="timeoutMSec">超時時間</param> public bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec) { TimeoutObject.Reset(); socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketC.BeginConnect(remoteEndPoint, CallBackMethod, socketC); //阻塞當前線程 if (TimeoutObject.WaitOne(timeoutMSec, false)) { return true; } else { return false; } } //--異步回調方法 private void CallBackMethod(IAsyncResult asyncresult) { //使阻塞的線程繼續 Socket socket = asyncresult.AsyncState as Socket; if (socket.Connected) { socket.EndConnect(asyncresult); } TimeoutObject.Set(); } public void testOnline(string msg) { socketC.Send(Encoding.GetEncoding("gb2312").GetBytes(msg)); try { //創建一個通信線程 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg); Thread thr = new Thread(pts); thr.IsBackground = true; //啟動線程 thr.Start(socketC); } catch { throw ;} } /// <summary> /// 接收客戶端發來的信息 /// </summary> /// <param name="socketClientPara">客戶端套接字對象</param> private void ServerRecMsg(object socketClientPara) { Socket socketServer = socketClientPara as Socket; byte[] arrServerRecMsg = new byte[100]; int len; while ((len = socketServer.Receive(arrServerRecMsg)) != 0) { //將機器接受到的字節數組轉換為人可以讀懂的字符串 recMsg = Encoding.Default.GetString(arrServerRecMsg, 0, len); if (recMsg == "online") { break; } } } }