我在尝试在简单的 Java 套接字客户端和简单的 C 套接字服务器之间来回发送字符串时遇到问题。
它的工作原理如下:
Java客户端发送msg
到C服务器
out.writeBytes(msg);
C服务器接收到msg并放入buf
if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
C 服务器将消息发送回 Java 客户端
if ((len = send(new_fd, buf, numbytes, 0)) == -1)
perror("send");
但是 Java 客户端无法从 C 服务器接收消息,我尝试使用DataInputStream
, BufferedReader
, 读入char[]
, byte[]
, 转换为string
但无法获取接收到的消息。当试图读入客户端的数组时,有时我只得到第一个字符,这让我相信这是一个阻塞问题?
任何帮助,将不胜感激
代码:
C服务器主循环
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if ((numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("msg size: '%d' bytes\n",numbytes);
printf("received msg: %s\n",buf);
char* array = (char*)buf;
printf("as char array: %s\n", array);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
int len = 0;
if ((len = send(new_fd, buf, numbytes, 0)) == -1)
perror("send");
printf("sent %d bytes\n", len);
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
Java 客户端
public void send(String text){
Socket sock = null;
DataInputStream in = null;
DataOutputStream out = null;
BufferedReader inReader = null;
try {
sock = new Socket(HOST, PORT);
System.out.println("Connected");
in = new DataInputStream(sock.getInputStream());
out = new DataOutputStream(sock.getOutputStream());
out.writeBytes(text + "\n");
String res = "";
//get msg from c server and store into res
System.out.println("Response: " + res);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
sock.close();
//in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}