using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace ONECONNECT
{
    public partial class Client : Form
    {
        private const int port = 11000;
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);
        private static String response = String.Empty;
        private string message = string.Empty;
        Socket client;
        public Client()
        {
            InitializeComponent();
        }        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                client.EndConnect(ar);
                response = "Socket connected to " + client.RemoteEndPoint.ToString();
                MethodInvoker mi = new MethodInvoker(UpContrlData);
                this.BeginInvoke(mi);
                connectDone.Set();
            }
            catch
            {
                message = "目标机器未启动,请检查!";
                MethodInvoker mi = new MethodInvoker(UpContrlDataMessage);
                this.BeginInvoke(mi);
                connectDone.Set();
            }
        }        private static void Receive(Socket client)
        {
            try
            {
                StateObject state = new StateObject();
                state.workSocket = client;
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                int bytesRead = client.EndReceive(ar);                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                    }
                    else
                    {
                        response = " ";
                    }
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                    receiveDone.Set();
                }
                else
                {
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }        private static void Send(Socket client, String data)
        {
            try
            {
                byte[] byteData = Encoding.ASCII.GetBytes(data);
                client.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), client);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket client = (Socket)ar.AsyncState;
                int bytesSent = client.EndSend(ar);
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }        private void btnLink_Click(object sender, EventArgs e)
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();
        }        private void UpContrlData()
        {
            this.richTextBox1.AppendText("\n" + response);
        }        private void UpContrlDataMessage()
        {
            this.lbTemp.Text=message;
        }        private void btnSend_Click(object sender, EventArgs e)
        {
            
            Send(client, this.textBox1.Text.Trim());
            sendDone.WaitOne();            Receive(client);
            receiveDone.WaitOne();
            MethodInvoker mi = new MethodInvoker(UpContrlData);
            this.BeginInvoke(mi);
            // Write the response to the console.
            // Release the socket.
            //client.Shutdown(SocketShutdown.Both);
            //client.Close();
        }
    }
}
上面是个简单的SOCKE客户端代码,连接上后,一直只有第一次发送成功。
之后发送不报错,但就是发送不到服务端。
求大虾看看哪里有问题?

解决方案 »

  1.   

    http://www.cnblogs.com/ljq124/articles/231185.html
      

  2.   

           
            public void StartListening()
            {
                byte[] bytes = new Byte[1024];
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
                Socket listener = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    listener.Bind(localEndPoint);
                    listener.Listen(100);
                    while (true)
                    {
                        allDone.Reset();
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
                        allDone.WaitOne();
                        MethodInvoker mi = new MethodInvoker(UpContrlDataCount);
                        this.BeginInvoke(mi);
                    }            }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }这个是我服务端的代码,现象确实如楼上所说,服务端不支持长连接。
    楼上能不能详细点?
      

  3.   


          public void StartListening()
            {
                byte[] bytes = new Byte[1024];
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
                Socket listener = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    listener.Bind(localEndPoint);
                    listener.Listen(100);
                    while (true)
                    {
                        allDone.Reset();
                        listener.BeginAccept(
                            new AsyncCallback(AcceptCallback),
                            listener);
                        allDone.WaitOne();
                        MethodInvoker mi = new MethodInvoker(UpContrlDataCount);
                        this.BeginInvoke(mi);
                    }            }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }        public  void AcceptCallback(IAsyncResult ar)
            {
                allDone.Set();
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
            }        public void ReadCallback(IAsyncResult ar)
            {
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));
                    content = state.sb.ToString();
                    MethodInvoker mi = new MethodInvoker(UpContrlData);
                    this.BeginInvoke(mi);
                    Send(handler, content);
                }
            }        private void Send(Socket handler, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);            // Begin sending the data to the remote device.
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
            }        private 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);
                    //this.rtxtContent.AppendText("\n" + bytesSent.ToString());                //handler.Shutdown(SocketShutdown.Both);
                    //handler.Close();            }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }        private void btnStart_Click(object sender, EventArgs e)
            {
                this.rtxtContent.AppendText(">>开始监听");
                Thread th = new Thread(new ThreadStart(StartListening));
                th.Start();
                this.btnStart.Enabled = false;
            }
    上面是服务端的代码。
    帮忙看看。
      

  4.   

    你的异步接收的代码看着很别扭,多写了一层,而且每次接收后应该再调一次接收函数,这样下次才能接收到IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                buffer = new byte[65535];
                //获取本机ip,本机监听端口号从ini文件中获得
                MyServer = new IPEndPoint(IPAddress.Parse(ipHost.AddressList[0].ToString()), Convert.ToInt32(myport));
                Clientip = (EndPoint)MyServer;
                ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               
                ListenerSocket.Bind(MyServer);
                ListenerSocket.Listen(50);
                          //循环监听
                while (true)
                {
                    socketConnection = ListenerSocket.Accept();
                    socketConnection.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(recv), socketConnection);
                }/// <summary>
            /// 异步接收
            /// </summary>
            /// <param name="iar"></param>
            public static void recv(IAsyncResult iar)
            {
                try
                {
                    int num = socketConnection.EndReceive(iar);
                    if (num == 0) return; 
                    var command = Encoding.Default.GetString(buffer, 0, num);
                    MessageBox.Show(command);
    //一次接收后应该再调接受函数一次,否则下次接收不到。
                    socketConnection.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(recv), ListenerSocket);
                }
                catch
                {
                    socketConnection.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(recv), ListenerSocket);
                }
            }
      

  5.   

    楼上请仔细修改楼主的代码,而不是贴一段糟糕代码出来(MessageBox.Show没有回调,try-catch误用,catch中要关闭socket,否则还是报错)。楼主只要在SendCallback函数中,原来注释掉关闭socket的地方,添加BeginReceive即可,这样就可以让客户端继续发送了。另外要注意catch处将Socket关闭,特别是BeginReceive的回调函数中,要关闭Socket。除了异常关闭Socket外,客户端主动关闭连接时也要关闭,判断依据是:
    if (bytesRead > 0)
    {}
    else
    {
    //客户端已经关闭连接,服务端这里也必须关闭
    }
      

  6.   

    to8L:我主要是说问题.现写的函数