public class XmlSocket { //异步socket诊听 // Incoming data from client.从客户端传来的数据 public static string data =null; // Thread signal.线程 用一个指示是否将初始状态设置为终止的布尔值初始化 ManualResetEvent 类的新实例。 public static ManualResetEvent allDone =new ManualResetEvent(false); //static void Main(string[] args) //{ // StartListening(); //} public static void StartListening() { // Data buffer for incoming data. 传入数据缓冲 byte[] bytes =new Byte[1024]; // Establish the local endpoint for the socket. 建立本地端口 // The DNS name of the computer // running the listener is "host.contoso.com". IPAddress ipAddress; String ipString = ConfigurationManager.AppSettings.Get("SocketIP"); if (ipString==null|| ipString ==String.Empty) { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); ipAddress = ipHostInfo.AddressList[0]; } else { ipAddress = IPAddress.Parse(ipString); } int port; String portString = ConfigurationManager.AppSettings.Get("SocketPort"); if (portString==null || portString==String.Empty) { port =11001; } else { port =int.Parse(portString); } IPEndPoint localEndPoint =new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket listener =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections.绑定端口和数据 try { listener.Bind(localEndPoint); listener.Listen(100); while (true) { // Set the event to nonsignaled state.设置无信号状态的事件 allDone.Reset(); // Start an asynchronous socket to listen for connections.重新 启动异步连接 listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing.等待连接创建后继续 allDone.WaitOne(); } } catch (Exception e) { // } } public static void AcceptCallback(IAsyncResult ar) { try { // Signal the main thread to continue.接受回调方法 该方法的此节向主应用程序线程发出信号, //让它继续处理并建立与客户端的连接 allDone.Set(); // Get the socket that handles the client request.获取客户端请求句柄 Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state =new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } catch (Exception e) { // } } /// <summary> /// 与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。 /// 该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。 /// 从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。 /// </summary> /// <param name="ar">IAsyncResult 委托</param> public static void ReadCallback(IAsyncResult ar) { try { String content = String.Empty; // Retrieve the state object and the handler socket创建自定义的状态对象 from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket;//处理的句柄 // Read data from the client socket. 读出 int bytesRead = handler.EndReceive(ar); if (bytesRead >0) { //业务代码 string result = DoSomeThing(...); String len = Encoding.UTF8.GetBytes(result).Length.ToString().PadLeft(8, '0'); log.writeLine(len); Send(len + result, handler); } } catch (Exception e) { // } } private static void Send(String data, Socket handler) { try { // Convert the string data to byte data using UTF8 encoding. byte[] byteData = Encoding.UTF8.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } catch (Exception e) { // } } /// <summary> /// 发送 /// </summary> /// <param name="ar"></param> private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket handler = (Socket)ar.AsyncState; // Complete sending the data to the remote device.向远端发送数据 int bytesSent = handler.EndSend(ar); StateObject state =new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { // } } public static void StopListening() { allDone.Close(); log.close(); } /// <summary> /// 具体处理业务的方法 /// </summary> /// <returns></returns> private static string DoSomething(int i) { //具体业务代码,返回需要返回的字符串信息 } /// <summary> /// 写日志方法 /// </summary> /// <param name="strLog">写入内容</param> public static void WriteLog(string strLog) { //写入日志代码 } } |