I am trying to create a basic client/server system in C for a project. I have the basis of the idea down…I have a while loop in my client executing infinitely until the server sends the kill signal for now. I am reading/writing blocks. I managed to get the first read/write to work with the server, but then it’s not working afterwards.
I am fairly sure I am doing something wrong with the sockets. The idea is I want the server to wait until the client sends another write() command. Here is what I have on the server/client:
Client
short connected = 1;
do
{
// Send initial request on first pass
// Afterwards send the resposne we were given
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
error("Failed to send messege. Terminating.");
printf("%s\n", buffer);
// Any errors?
if (strcmp(buffer, "Session key does not match. Terminating.") == 0)
error(buffer);
// Get session key response
bzero(buffer, BUFFER_LENGTH);
n = read(sockfd, buffer, BUFFER_LENGTH);
if (n < 0)
error("Could not fetch result. Terminating.");
printf("%s\n", buffer);
sleep(1);
} while (connected == 1);
Server
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("Error opening socket.\n");
exit(0);
}
// Taken from reference
bzero((char *) &serv_addr, sizeof(serv_addr));
portNumber = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portNumber);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
printf("ERROR on binding.\n");
close(sockfd);
exit(0);
}
// Add listner to socket and wait until we are given something to do
// Taken from reference
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
printf("ERROR on accept.\n");
close(sockfd);
exit(0);
}
// Get initial session key request
bzero(buffer,BUFFER_LENGTH);
n = read(newsockfd, buffer, BUFFER_LENGTH);
if (n < 0)
{
printf("ERROR reading from socket.\n");
close(newsockfd);
close(sockfd);
exit(0);
}
// ... a bunch of processing of data
n = write(newsockfd, response, lengthOfKey + 15 + 1);
if (n < 0)
{
printf("ERROR writing to socket.\n");
close(newsockfd);
close(sockfd);
exit(0);
}
close(newsockfd);
// Get the previous key(s) now (we hope)
short connected = 1;
while (connected < 100)
{
printf("waiting...\n");
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
//... more processing
}
Thanks to the comments I found out that the read() block will stop the server code until it is given something from the client via write(). All working 🙂 Thanks