我在尝试在简单的Java套接字客户端和简单的C套接字服务器之间来回发送字符串时遇到问题。
它的工作原理如下:
Java客户端将msg
发送到C服务器
out.writeBytes(msg);
C服务器收到消息并放入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[]
,转换为{ {1}}但无法收到收到的消息。当试图在客户端读取数组时,我有时只会得到第一个让我相信它是阻塞问题的字符?
任何帮助将不胜感激
代码:
C服务器主循环
string
Java客户端
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
}