消息未发送:C套接字

时间:2017-08-07 17:20:48

标签: c

执行后,我在客户端输入文件名,但不在服务器端打印。尝试了一切。请帮忙。我在windows中使用bash。我只是从客户端向服务器发送文件名。服务器端将显示客户端。

这是我的client.c

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
  int main()
  {
    int i,size,connect_status,sd;
    char sentmsg[100],recvmsg[100];
    int sentlen,sent_status,recvlen,recvbytes;
    struct sockaddr_in client,address;
    sd = socket(AF_INET,SOCK_STREAM,0);
    if(sd == -1)
    {
            perror("Socket Error : ");
            return 0;
    }

    client.sin_family = AF_INET;
    client.sin_port = htons(1543);
    client.sin_addr.s_addr = INADDR_ANY;
    for(i=0; i<8;i++)
    {
            client.sin_zero[i] = '\0';
    }
    connect_status = connect(sd,(struct sockaddr*)&client,sizeof(struct sockaddr));
    if(connect_status == -1)
    {
            perror("Connect Error : ");
            return 0;
    }
    printf("\nEnter the file name to be read : ");
    scanf("%s",sentmsg);
    sent_status = send(sd,sentmsg,100,0);
    if(sent_status == -1)
    {
            perror("Sending Error : ");
            return 0;
    }

    return 0;
  }

这是我的server.c

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
int main()
{
    int i,newsd,sd,size,listen_status,bind_status,fd;
    char sentmsg[100],recvmsg[100];
    int sent_status,rec_status,sentlen,recvlen;
    struct sockaddr_in server,address;
    sd = socket(AF_INET,SOCK_STREAM,0);
    if(sd == -1)
    {
            perror("Socket Error : ");
            return 0;
    }
    server.sin_family = AF_INET;
    server.sin_port = htons(1534);
    server.sin_addr.s_addr = INADDR_ANY;
    for(i=0 ; i<8 ; i++)
    {
            server.sin_zero[i] = '\0';
    }
    bind_status = bind(sd,(struct sockaddr*)&server,sizeof(struct sockaddr));
    if(bind_status == -1)
    {
            perror("\nBind Error : ");
            return 0;
    }
    listen_status = listen(sd,5);
    if(listen_status == -1)
    {
            perror("\nListen Error : ");
            return 0;
    }
    size = sizeof(struct sockaddr_in);
    newsd = accept(sd,(struct sockaddr*)&address,&size);
    if(newsd == -1)
            {
            perror("\nAccept Error : ");
            return 0;
    }
    rec_status = recv(newsd,recvmsg,recvlen,0);
    if(rec_status == -1)
    {
            perror("\nRecieve Error : ");
            return 0;
    }
    recvmsg[rec_status] = '\0';
    printf("\nClient : %s",recvmsg);
    return 0;
}

我无法从客户端向服务器发送消息。请帮忙

1 个答案:

答案 0 :(得分:0)

因为你没有初始化recvlen。 将其设置为接收缓冲区长度,它将起作用:

recvlen = 100;
rec_status = recv(newsd,recvmsg,recvlen,0);