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 测试客户端可以很好地读取输出。
希望有人对如何使这项工作有一些想法,我对任何解决方案持开放态度。