我正在开发客户端-服务器应用程序。客户端基于 Java,服务器端是 Windows 中的 C++。
我试图用套接字与它们通信,但我遇到了一些麻烦。
我已经成功地将客户端与 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 中)? 我自己做不到。
谢谢。
最佳答案
你的问题是你正在发送一个 java 字符串,每个字符可能需要 1 或 2 个字节(参见 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;
其中是
,os
分别是客户端DataInputStream
和DataOutputStream
。
您还可以嗅探您的 tcp 流量以查看发生了什么:)
关于java - 如何针对 Java 客户端实现 C++ 套接字服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9162830/