2012-02-06 89 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

相关问题