繁体   English   中英

TCP侦听套接字错误

[英]TCP listen socket error

我有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);

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

长话短说,TCP / IP协议具有连接建立阶段。 因此,服务器必须调用bind()listen()accept() ,而客户端必须调用connect() 建立连接后,服务器accept()返回一个新的客户端-服务器套接字。 该套接字允许服务器与客户端进行通信(即为连接提供服务)。

我向您推荐以下示例:

  1. 同步服务器套接字示例
  2. 同步客户端套接字示例

该代码应该是这样的

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)
    {
    }

  }

试试这个代码

           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);
                    }

               } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM