TCP侦听套接字错误

时间:2012-08-03 09:17:23

标签: c# sockets

我有2个程序,客户端和服务器,客户端程序通过 TCP 协议通过特定端口(EX:1370)发送数据。
我使用以下代码在我的服务器程序中等待客户端。

IPAddress IP = (my IP Address);
IPEndPoint ipep = new IPEndPoint(IP, 1370);

listenSocket = new Socket(AddressFamily.InterNetwork, 
                          SocketType.Stream, 
                          ProtocolType.Tcp);
listenSocket.Bind((EndPoint) ipep);
listenSocket.BeginReceive(clientData, 0, clientData.Length,
                          SocketFlags.None, new AsyncCallback(OnReceiveClient), null);

我在最后一行有错误,socket无法在TCP协议中接收数据。 这段代码在UDP协议中工作得很好。 你能帮助我吗?! (感谢)

3 个答案:

答案 0 :(得分:2)

长话短说,TCP / IP协议具有连接建立阶段。因此,服务器必须致电bind()listen()accept(),客户必须致电connect()。建立连接后,服务器accept()将返回新客户端 - 服务器套接字。此套接字允许服务器与客户端通信(即提供连接)。

我想向您推荐以下示例:

  1. Synchronous Server Socket Example
  2. Synchronous Client Socket Example

答案 1 :(得分:1)

代码应该是这样的

IPAddress IP = (my IP Address);
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint ipep = new IPEndPoint(IP, 1370);
listenSocket.Bind((EndPoint) ipep);

listenSocket.Listen(4);
// Create the call back for any client connections...
listenSocket.BeginAccept(new AsyncCallback (OnClientConnect), null);

一旦客户端连接

// This is the call back function, which will be invoked when a client is connected
 public void OnClientConnect(IAsyncResult asyn)
 {
   try
   {
        Socket workerSocket = m_mainSocket.EndAccept (asyn);        
        workerSocket.BeginReceive();                    
        // Since the main Socket is now free, it can go back and wait for
        // other clients who are attempting to connect
        m_mainSocket.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
   }
   catch(ObjectDisposedException)
    {
    }
    catch(SocketException se)
    {
    }

  }

答案 2 :(得分:0)

试试此代码

           public void Listen()
            {
            string portStr = "5656";
            int port = System.Convert.ToInt32(portStr);
            // Create the listening socket...
            m_mainSocket = new Socket(AddressFamily.InterNetwork,                            SocketType.Stream,ProtocolType.Tcp);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
            // Bind to local IP Address...
            m_mainSocket.Bind(ipLocal);
            // Start listening...
             m_mainSocket.Listen(4);
             btn_start.Enabled = false;
             lbl_connect.Visible = true;
            // Create the call back for any client connections...
            m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
           }



             public void OnClientConnect(IAsyncResult asyn)
             {
             m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
            // Let the worker Socket do the further processing for the 
            // just connected client
            WaitForData(m_workerSocket[m_clientCount]);
            // Now increment the client count
            ++m_clientCount;
            // Display this client connection as a status message on the GUI    


            // Since the main Socket is now free, it can go back and wait for
            // other clients who are attempting to connect
            m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

// **等待客户数据

            public void WaitForData(System.Net.Sockets.Socket soc)
            {
                try
                {
                   if (pfnWorkerCallBack == null)
                   {
                       // Specify the call back function which is to be 
                      // invoked when there is any write activity by the 
                      // connected client
                      pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                   }
                    SocketPacket theSocPkt = new SocketPacket();
                    theSocPkt.m_currentSocket = soc;
                   // Start receiving any data written by the connected client
                   // asynchronously
                    soc.BeginReceive(theSocPkt.dataBuffer, 0,                                                      theSocPkt.dataBuffer.Length,
                               SocketFlags.None,
                               pfnWorkerCallBack,
                               theSocPkt);
                    }
                    catch (SocketException se)
                    {
                        MessageBox.Show(se.Message);
                    }

               }