I would like to communicate with 2 applications : a client in C which send a message to the server in TCP and the server in Java which receive it and send an acknowledgement.
Here is the client (the code is a thread) :
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;
}
And the java server :
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);
}
With n = read(sockfd,buffer,255); the client is waiting a response and for the server, the message is never ended so it doesn't send a response with PrintStream.
If I remove these lines :
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) {
error("ERROR reading from socket");
}
printf("Message from the server : %s\n",buffer);
The server knows that the message is finished but the client can't receive the response.
How solve that ?
Thank you