0

Below is my socket client program. I am trying to send some data from client and trying to receive it in the client side. When I run the program, there is no compilation error. But I am unable to receive the sent message correctly in the client side. I think I am doing some error in

server_reply [len]='\0';
printf("%s\n", server_reply);

My original code is written below: (you can find my server program here in this link Multiple client not getting connected and cannot communicate at the same time)

#include<stdio.h> //printf
#include<string.h>    //strlen
#include<sys/socket.h>    //socket
#include<arpa/inet.h> //inet_addr

int main(int argc , char *argv[])
{
    int sock;
    struct sockaddr_in server;
    char message[1000] , server_reply[2000];
    int len;

    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 8888 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");

    //keep communicating with server
    while(1)
    {
        printf("Enter message : ");
        scanf("%s" , message);


        //Send some data
        if( send(sock , message , strlen(message) , 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if(len = (recv(sock , server_reply , 2000 , 0)) < 0)
        {
            puts("recv failed");
            break;
        }

        puts("Server reply :");
        server_reply [len]='\0';
    printf("%s\n", server_reply);


    }

    close(sock);

    return 0;
}
4

1 回答 1

0

这条线是错误的。

   if (len = (recv(sock , server_reply , 2000 , 0)) < 0)
    {
        puts("recv failed");
        break;
    }

应该:

   if ((len = recv(sock , server_reply , 2000 , 0)) < 0)
    {
        puts("recv failed");
        break;
    }
于 2014-07-07T04:41:05.460 回答