C中的TCP客户端和Java中的服务器

时间:2012-10-15 09:34:51

标签: java c tcp client-server

我想与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);

服务器知道邮件已完成,但客户端无法收到响应。

如何解决?

谢谢

1 个答案:

答案 0 :(得分:3)

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