2013-12-20 186 views
1

我在編碼3D一段時間,現在,我不想創建一個適用於網絡的遊戲。我使用System.Net和System.Net.Sockets。C#客戶端服務器TCP客戶端收聽

我的服務器是愚蠢的地獄,它只是能夠舉行一個單一的連接(稍後,我會改變它的多連接能力)。它有一個TcpListener,它在端口10000上的127.0.0.1上偵聽。(只是爲了測試)。在那裏,我有一個DO While While循環來檢查收到的數據並顯示它。

我的客戶端是一個TcpClient。它連接到服務器併發送消息。這裏沒什麼特別的,它是用TcpClient.GetStream()。Write()完成的。這很好。我也可以在發送之後閱讀一個答案。

但是如果服務器會在沒有客戶端詢問的情況下發送一些信息呢?例如:服務器上的所有玩家都會收到一個項目。我如何設置我的客戶端,才能夠收到此類消息?

我的客戶是否需要循環詢問?或者我必須以某種方式製作代表?我可以創建一個循環,每200毫秒或者其他地方要求這樣的信息,但是這將如何改變3D遊戲的性能?

這是如何在專業遊戲開發中完成的?

回答

0

使用異步客戶端套接字:

「客戶是建立與異步套接字,所以當服務器返回 響應 客戶端應用程序的執行不暫停」

http://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx

private static void ReceiveCallback(IAsyncResult ar) { 
     try { 
      // Retrieve the state object and the client socket 
      // from the asynchronous state object. 
      StateObject state = (StateObject) ar.AsyncState; 
      Socket client = state.workSocket; 

      // Read data from the remote device. 
      int bytesRead = client.EndReceive(ar); 

      if (bytesRead > 0) { 
       // There might be more data, so store the data received so far. 
      state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); 

       // Get the rest of the data. 
       client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, 
        new AsyncCallback(ReceiveCallback), state); 
      } else { 
       // All the data has arrived; put it in response. 
       if (state.sb.Length > 1) { 
        response = state.sb.ToString(); 
       } 
       // Signal that all bytes have been received. 
       receiveDone.Set(); 
      } 
     } catch (Exception e) { 
      Console.WriteLine(e.ToString()); 
     } 
    } 

在此ReceiveCallback您可以創建處理服務器的消息的開關。

例如: 消息的第一個字節是一個命令,在命令之後是正確的數據。在交換機中,您可以處理該命令並執行一些代碼。

0

使用TcpClient和TcpListener類的異步功能。
在您的客戶:

private TcpClient server = new TcpClient(); 

void listen(){ 
    try { 
     IPAddress IP = IPAddress.Loopback // this is your localhost IP 
     await server.ConnectAsync(IP,10000); // IP, port number 

     if(server.Connected) { 
      NetworkStream stream = server.GetStream(); 

      while (server.Connected) { 
       byte[ ] buffer = new byte[server.ReceiveBufferSize]; 
       int read = await stream.ReadAsync(buffer, 0, buffer.Length); 
       if (read > 0){ 
        // you have received a message, do something with it 
       } 
      } 
     } 
    } 
    catch (Exception ex) { 
     // display the error message or whatever 
     server.Close(); 
    } 
}