【发布时间】:2014-04-15 02:05:48
【问题描述】:
所以我编写了一个客户端/服务器程序,其中客户端是用 C++ 编写的,而服务器是用 Java 编写的。当我尝试向 java 端发送数据时,send() 函数失败并返回-1。我不知道是什么问题。
这里是客户端:
int main(){
string address = "127.0.0.1";
sockaddr_in socketInfo;//declare struct object
SOCKET socketClient;
WSAData network;
int errorNum;//networking functions return integer values that represent the success of the call to the function
errorNum = WSAStartup(MAKEWORD(2, 2), &network);
if (errorNum == 0){
socketInfo.sin_family = AF_INET;//set family to ipv4
socketInfo.sin_port = htons(6897);//set port to connect to and convert to network byte order htons
errorNum = inet_pton(socketInfo.sin_family, "127.0.0.1", &socketInfo.sin_addr);
socketClient = socket(socketInfo.sin_family, SOCK_STREAM, IPPROTO_TCP);//creates a socket
if (socketClient != INVALID_SOCKET){
errorNum = connect(socketClient, (sockaddr*)&socketInfo, sizeof(socketInfo));
if (errorNum != SOCKET_ERROR){
cout << "Connected to Java Application!" << endl;
int num = 152;
cout << "Trying to send..." << endl;
const char* buff = (const char*)(num);
errorNum = send(socketClient, buff, sizeof(buff), 0);
if (errorNum != SOCKET_ERROR)
cout << "sent with success " << errorNum << endl;
else
cout << "Failed to send " << errorNum << endl;
closesocket(socketClient);
}
else{
cout << "Failed to connect" << endl;
closesocket(socketClient);
}
}
else
cout << "Socket creation failed!" << endl;
}//end if
else
cout << "WSA startup failed" << endl;
WSACleanup();
//thread t1(getStroke, VK_SPACE);
//thread t2(getStroke, VK_ESCAPE);
//t1.join();
//t2.join();
system("pause");
return 0;
}
这里是服务器端:
try {
server = new ServerSocket(6897);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
new Thread(new Runnable() {
public void run() {
try {
System.out.println("Waiting on C++ Application...");
connection = server.accept();
System.out.println("Connected to C++ Application!");
setupStreams();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setupStreams() {
// TODO Auto-generated method stub
try {
input = new DataInputStream(connection.getInputStream());
int data = 0;
System.out.println("Waiting for data...");
data = input.read();
System.out.println("Data recieved " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
【问题讨论】:
-
大多数 send() 的实现都有获取更多信息的方法,比如 errno、socket 错误等。
-
也许 const char* buff = (const char*)(num) 应该是 const char* buff = (const char*)(&num) ? (通知 &num)
-
感谢所有给我建议的人!这怎么跑题了?管理员,请停止欺负您网站的用户。我不知道你们正在进行哪种类型的电力旅行,但请停下来。这怎么会缺乏足够的信息呢?您还希望我如何描述我的问题?我给出了所有相关的代码!
标签: java c++ sockets send serversocket