当前位置: 代码迷 >> .NET面试 >> C# socket异步侦听的有关问题
  详细解决方案

C# socket异步侦听的有关问题

热度:64   发布时间:2016-05-02 20:41:45.0
C# socket异步侦听的问题
C# code
IPHostEntry gist = Dns.GetHostByName("localhost");                    IPAddress ip = gist.AddressList[0];                    IPEndPoint IPEP = new IPEndPoint(ip, 6666);                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                    sock.Bind(IPEP);                    sock.Listen(10);                    _logger.Log("开启服务,开始侦听:"+IPEP.Port , Category.Info, Priority.Medium);                    while (true)                    {                        // 开始监听,这个方法会阻塞线程的执行,直到接受到一个客户端的连接请求                        Socket client = sock.Accept();                        // 输出客户端的地址                        _logger.Log(client.RemoteEndPoint.ToString(), Category.Info, Priority.Medium);                        // 准备读取客户端请求的数据,读取的数据将保存在一个数组中                        byte[] buffer = new byte[4096];                        // 接受数据                        int length = client.Receive(buffer, 4096, SocketFlags.None);                        // 将请求的数据翻译为 UTF-8                        System.Text.Encoding utf8 = System.Text.Encoding.UTF8;                        string requestString = utf8.GetString(buffer, 0, length);                        // 显示请求的内容                        Console.WriteLine(requestString);                        // 状态行                        string statusLine = "HTTP/1.1 200 OK\r\n";                        byte[] statusLineBytes = utf8.GetBytes(statusLine);                        // 准备发送到客户端的网页                        string responseBody                             = @"<?xml version='1.0' encoding='utf-8' ?>                                    <data>                                      <item>hfuyqiueoaiudiaojdalksjdn</item>                                    </data>";                        byte[] responseBodyBytes = utf8.GetBytes(responseBody);                        // 回应的头部                        string responseHeader = string.Format("Content-Type: text/xml; charset=UTF-8\r\nContent-Length: {0}\r\n",responseBody.Length);                        byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);                        // 向客户端发送状态信息                        client.Send(statusLineBytes);                        // 向客户端发送回应头                        client.Send(responseHeaderBytes);                        // 头部与内容的分隔行                        client.Send(new byte[] { 13, 10 });                        // 向客户端发送内容部分                        client.Send(responseBodyBytes);                        // 断开与客户端的连接                        client.Close();                        if (Console.KeyAvailable)                            break;                    }                    // 关闭服务器                    sock.Close();

这是我socket侦听代码,请高手帮我改成多线程+异步的,谢谢!~~

------解决方案--------------------
给个模板自己照着该。

C# code
        private void button1_Click(object sender, System.EventArgs e)        {            try            {                myIP = IPAddress.Parse(textBox1.Text);            }            catch { MessageBox.Show("您输入的IP地址格式不正确,请重新输入!"); }            try            {                MyServer = new IPEndPoint(myIP, Int32.Parse(textBox2.Text));                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                sock.Bind(MyServer);                sock.Listen(50);                statusBarPanel1.Text = "主机" + textBox1.Text + "端口" + textBox2.Text + "开始监听......";                //aaa=sock.Accept();                Thread thread = new Thread(new ThreadStart(targett));                thread.Start();            }            catch (Exception ee) { statusBarPanel1.Text = ee.Message; }        }        private void targett()        {            while (true)            {                Done.Reset();                sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);                Done.WaitOne();            }        }        private void AcceptCallback(IAsyncResult ar)        {            Done.Set();            Socket listener = (Socket)ar.AsyncState;            handler = listener.EndAccept(ar);            StateObject state = new StateObject();            state.workSocket = handler;            this.BeginInvoke( new MethodInvoker(     delegate()     {         statusBarPanel1.Text = "与客户建立连接。";     }));            try            {                byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!" + "\n\r");                handler.BeginSend(byteData, 0, byteData.Length, 0,                    new AsyncCallback(SendCallback), handler);            }            catch (Exception ee) { MessageBox.Show(ee.Message); }            Thread thread = new Thread(new ThreadStart(rec));            thread.Start();        }        private void rec()        {            StateObject state = new StateObject();            state.workSocket = handler;            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,            new AsyncCallback(ReadCallback), state);        }        private void ReadCallback(IAsyncResult ar)        {            StateObject state = (StateObject)ar.AsyncState;            Socket tt = state.workSocket;            int bytesRead = handler.EndReceive(ar);            state.sb.Append(System.Text.Encoding.BigEndianUnicode.GetString(                state.buffer, 0, bytesRead));            string content = state.sb.ToString();            state.sb.Remove(0, content.Length);            this.BeginInvoke(new MethodInvoker(delegate() { richTextBox1.AppendText(content + "\r\n"); }));            tt.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,                new AsyncCallback(ReadCallback), state);        }        private void SendCallback(IAsyncResult ar)        {            try            {                handler = (Socket)ar.AsyncState;                int bytesSent = handler.EndSend(ar);            }            catch            {                MessageBox.Show("!");            }        }    /// <summary>    ///     /// </summary>    public class StateObject    {                public Socket workSocket = null;       // Client  socket.        public const int BufferSize = 1024;       // Size of receive buffer.        public byte[] buffer = new byte[BufferSize]; // Receive buffer.        public StringBuilder sb = new StringBuilder();  // Received data string.        public StateObject()        {            //             // TODO: 在此处添加构造函数逻辑            //          }    }
  相关解决方案