简体   繁体   中英

Socket error in C using read and write functions

I am attempting to read and write to a socket using linux networking programming in C. I make successful calls to "write" and "read" in the client and server programs respectively.

The part I am having difficulty understanding is that on my client program, I loop and call the write 5 different times, on the server, I loop and call the read 5 different times.

This is the expected output:

MSG: I got your message MSG: I got your message MSG: I got your message MSG: I got your message MSG: I got your message

This is the actual output:

MSG: I got your messageI got your messageMSG: I got your messageI got your messageMSG: I got your messageMSG: MSG:

As you can see the expected output and the actual output are different. It looks like the client is able to call "write" twice before it is actually sent.

This is what I have for the client code

for(int i=0;i<5;i++)
{   
    int n = write(ssocket.socketFileDescriptor,"I got your message",18);
    cout<<n<<" number of bytes written."<<endl;
    if (n < 0) socketError("ERROR writing to socket");
}

This is the server code:

void* run(void* arg)
{
    ServerSocket* ss = (ServerSocket*)arg;
    //while(true)
    for(int i=0;i<5;i++)
    {
        char buffer[256];
        bzero(buffer,256);
        int n = read(ss->newsockfd,buffer,256);
        printf("MSG: %s",buffer);
    }
    close(ss->newsockfd);
}

This is an addition to the question below which is out of date at this point.

Am I missing a call to flush or something?

Simulate Java's Thread class in C++

Your client and server are just not coordinated. The client writes the message 5 times as quickly as it can, and the server reads five times as quickly as it can. In your example output, evidently on your first call to read() the client has sent the message twice, and on the second call to read() it's sent it a further two times. You read() up to 256 characters, and each time you call it, it will just attempt to read anything that's currently in the buffer. If the client has send multiple messages by that time, read() will just grab everything.

You typically need some type of synchronization, eg after you send one message, your client waits for the server to send "OK" or something similar before it sends the second message. Short of that, you can use some kind of end-of-message marker (such as a newline) so the server can differentiate them, if you have a very simple communication format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM