2012-08-03 178 views
-1

我有2個程序,客戶端和服務器,客戶端程序通過TCP協議發送特定端口的數據(EX:1370)。
我使用下面的代碼來等待我的服務器程序中的客戶端。TCP監聽套接字錯誤

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協議中工作得很好。 你能幫我嗎?! (感謝)

+1

「我有一個錯誤」 是很模糊的 - 你可以提供更多的細節? – 2012-08-03 09:19:16

+2

偵聽套接字通常用於接受連接,而不是接收數據。 UDP的交互與TCP的交互不同。你可能想看看這樣的東西:http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx – forsvarir 2012-08-03 09:27:58

+0

喬恩,錯誤是:「一個請求發送或接收數據被禁止,因爲套接字未連接,並且(當使用sendto調用在數據報套接字上發送時)沒有提供地址「 – user1518295 2012-08-03 09:28:58

回答

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

    } 
+0

非常感謝你......這段代碼工作得很好。謝謝。 – user1518295 2012-08-03 09:49:19

2

長話短說,TCP/IP協議有連接建立階段。所以服務器必須調用bind(),listen()accept(),客戶端必須調用connect()。連接建立後,服務器accept()返回一個新客戶端服務器套接字。該套接字允許服務器與客戶端進行通信(即服務於連接)。

我想向您推薦下面的例子:

  1. Synchronous Server Socket Example
  2. Synchronous Client Socket Example
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); 
        } 

       }