日期:2014-05-18 浏览次数:21069 次
ipAddress = IPAddress.Parse("0.0.0.0"); localEndPoint = new IPEndPoint(ipAddress, 2012); this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(localEndPoint); serverSocket.Listen(100); serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket); public StateObject state; public IPAddress ipAddress; public IPEndPoint localEndPoint; public Socket serverSocket; public static String receive; public void ListenFlow() { ipAddress = IPAddress.Parse("0.0.0.0"); localEndPoint = new IPEndPoint(ipAddress, 2012); this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(localEndPoint); serverSocket.Listen(100); serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket); } public void AcceptCallback(IAsyncResult ar)//启动异步接收数据 { try { Socket serverSocket = (Socket)ar.AsyncState; Socket clientSocket = serverSocket.EndAccept(ar); state = new StateObject(); state.workSocket = clientSocket; Send("connected"); this.serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), this.serverSocket); clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } catch (Exception e) { MessageBox.Show(e.ToString()); } } public void ReadCallback(IAsyncResult ar) { try { StateObject state = (StateObject)ar.AsyncState; Socket clientSocket = state.workSocket; int bytesRead = clientSocket.EndReceive(ar); if (bytesRead > 0) { byte[] str = state.buffer; Flowfairy.FlowSocket.receive = Convert.ToString(str[0]); if (Flowfairy.FlowSocket.receive == "1") { Send(Flowfairy.FlowSocket.receive);//每次执行这一行,就提示中断连接 } } Thread.Sleep(1); clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } catch (Exception e) { MessageBox.Show(e.ToString()); } } private void Send(String data) { byte[] byteData = Encoding.UTF8.GetBytes(data); state.workSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state.workSocket); } private void SendCallback(IAsyncResult ar) { try { Socket clientSocket = (Socket)ar.AsyncState; int bytesSent = clientSocket.EndSend(ar); } catch (Exception e) { MessageBox.Show(e.ToString()); } }