2

我想与 2 个应用程序通信:C 中的客户端向 TCP 中的服务器发送消息,Java 中的服务器接收并发送确认。

这是客户端(代码是一个线程):

static void *tcp_client(void *p_data)
{
  if (p_data != NULL)
  {
    char const *message = p_data;

    int sockfd, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("ERROR opening socket");
    }

    server = gethostbyname(ALARM_PC_IP);

    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(TCP_PORT);

    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
        error("ERROR connecting");
    }

    n = write(sockfd,message,strlen(message));

    if (n < 0) {
        error("ERROR writing to socket");
    }

    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0) {
      error("ERROR reading from socket");
    }
    printf("Message from the server : %s\n",buffer);
    close(sockfd);
  }

  return 0;
}

和java服务器:

try {
    int port = 9015;
    ServerSocket server=new ServerSocket(port);
    System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":"+port);
    System.out.println("Run the Client");

    while (true) {
        Socket socket=server.accept();
        BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(in.readLine());
        PrintStream out=new PrintStream(socket.getOutputStream());
        out.print("Welcome by server\n");
        out.flush();
        out.close();
        in.close();
        System.out.println("finished");
    }
} catch(Exception err) {
    System.err.println("* err"+err);
}

使用 n = read(sockfd,buffer,255); 客户端正在等待响应,对于服务器,消息永远不会结束,因此它不会使用 PrintStream 发送响应。

如果我删除这些行:

bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) {
  error("ERROR reading from socket");
}
printf("Message from the server : %s\n",buffer);

服务器知道消息已完成,但客户端无法接收响应。

怎么解决?

谢谢

4

1 回答 1

3

in.readLine() 等待流中的 NL、CR 或 CR+NL。确保您在客户消息中发送。

于 2012-10-15T09:49:54.757 回答