gpt4 book ai didi

java - 从 Java 读取 C 套接字挂起/阻塞

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:24 26 4
gpt4 key购买 nike

我在 Java 和 C 之间的套接字方面遇到问题。我有一个创建套接字并开始监听的 C 程序。 Java 客户端执行它的工作,在某些情况下打开一个套接字并写入它并尝试从中读取,但这会阻塞。

C 程序的套接字部分如下:

int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
char wbuffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
cout << "ERROR opening socket" << endl;
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 23456;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
int on = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
cout << "Couldn't set socket params!" << endl;
int so = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
while(so < 0) {
cout << "ERROR on binding" << endl;
sleep(1);
so = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
cout << "ERROR on accept" << endl;
bzero(buffer,256);
//cout << "Socket created!" << endl;
n = read(newsockfd,buffer,255);
if (n < 0)
cout << "Error reading from socket" << endl;
if (strcmp(buffer, "power\n") == 0) {
// Do stuff
strcpy(wbuffer, "off\n");
}
//sleep(1);
n = write(newsockfd,wbuffer,strlen(wbuffer));
if (n < 0)
cout << "ERROR writing to socket" << endl;
}
//cout << "message: " << buffer << endl;
close(newsockfd);
close(sockfd);

Java 方面:

Socket socket3 = new Socket("localhost", 23456);
PrintWriter out3 = new PrintWriter(socket3.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket3.getInputStream()));
out3.write("power" + "\n");
//String status = in.readLine();
log.debug("Wrote power");
StringBuffer buffer = new StringBuffer();
while (true) {
int ch = in.read();
log.debug("in.read()");
if ((ch < 0) || (ch == '\n')) {
break;
}
buffer.append((char) ch);
}
String status = buffer.toString();
out3.close();
in.close();
socket3.close();

写作有效,我做了一些调试,这是阅读,特别是 in.read(),这是最后完成的事情。

我可能在 Java 方面遗漏了一些东西,因为 C 测试客户端可以很好地读取输出。

希望有人知道如何使它正常工作,我愿意接受任何解决方案。

最佳答案

您的 C++ 代码非常糟糕。考虑一下如果 read(2) 返回的值小于 6 会发生什么。总的来说:

n = read(newsockfd,buffer,255);

if (n < 0)
cout << "Error reading from socket" << endl;

// continuing processing after an error - BAD

// not paying attention to n - BAD
if (strcmp(buffer, "power\n") == 0) {
// Do stuff
strcpy(wbuffer, "off\n");
}

// potentially writing zero bytes here - BAD
n = write(newsockfd,wbuffer,strlen(wbuffer));

if (n < 0)
cout << "ERROR writing to socket" << endl;

} // WHERE DID THIS PAREN COME FROM?

所以解决这些问题。检查 tcpdump(1)wireshark你在电线上得到什么。在两面打印出您的输入。您可能会发现您的假设在某处偏离了。

关于java - 从 Java 读取 C 套接字挂起/阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com