2012-02-06 43 views
2

林開發客戶端 - 服務器應用程序。客戶端是基於Java的,服務器端是Windows中的C++。如何針對java客戶端實現一個C++套接字服務器?

我試着去與他們溝通插座,但遇到一些麻煩IM。

我已成功傳達的客戶端與Java服務器,以測試是否是我的客戶,這是錯誤的,但它不是,好像我不是這樣做是正確的C++版本。

Java服務器是這樣的:

import java.io.DataInputStream; 
    import java.io.DataOutputStream; 
    import java.io.IOException; 
    import java.net.ServerSocket; 
    import java.net.Socket; 


    public class Server { 

    public static void main(String[] args){ 
     boolean again = true; 
     String mens; 
     ServerSocket serverSocket = null; 
     Socket socket = null; 
     DataInputStream dataInputStream = null; 
     DataOutputStream dataOutputStream = null; 

     try { 
     serverSocket = new ServerSocket(12321); 
     System.out.println("Listening :12321"); 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     } 

     while(again){ 
     try { 
      System.out.println("Waiting connection..."); 
     socket = serverSocket.accept(); 
     System.out.println("Connected"); 
     dataInputStream = new DataInputStream(socket.getInputStream()); 
     dataOutputStream = new DataOutputStream(socket.getOutputStream()); 
     while (again){ 
      mens = dataInputStream.readUTF(); 
      System.out.println("MSG: " + mens); 
      if (mens.compareTo("Finish")==0){ 
       again = false; 
      } 
     } 
     } catch (IOException e) { 
      System.out.println("End of connection"); 
     //e.printStackTrace(); 
     } 
     finally{ 
     if(socket!= null){ 
     try { 
      socket.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      //e.printStackTrace(); 
     } 
     } 

     if(dataInputStream!= null){ 
     try { 
      dataInputStream.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 

     if(dataOutputStream!= null){ 
     try { 
      dataOutputStream.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 
     } 
     } 
     System.out.println("End of program"); 
    } 
    } 

客戶端只建立連接,併發送用戶介紹了一些消息。

能否請你給我一個類似的工作服務器,但在C++(在Windows)? 我不能讓它自己工作。

感謝名單。

+0

客戶端代碼以及粘貼,並從你的服務器端日誌跟蹤。 – Sid 2012-02-06 17:00:32

+0

此外,一個簡單的谷歌搜索,就會發現數百,甚至數千的例子和教程製作一個套接字服務器在Windows中,。 – 2012-02-07 06:40:26

回答

0

你的問題是,你要發送這可能需要每個字符1或2個字節一個java字符串(見bytes of a string in java?

您需要發送和ASCII字節接收使事情變得更容易,想象data是你的在客戶端數據串:

byte[] dataBytes = data.getBytes(Charset.forName("ASCII")); 

for (int lc=0;lc < dataBytes.length ; lc++) 
{ 
    os.writeByte(dataBytes[lc]); 
} 

byte responseByte = 0; 
char response = 0; 

responseByte = is.readByte(); 
response = (char)responseByte; 

is哪裏和os分別DataInputStreamDataOutputStream是客戶端。

您也可以嗅出你的TCP流量,看看發生了什麼事情:)

+0

我會看看這個,thanx :) – Alex 2012-02-07 16:35:25

相關問題