我写了一个简单的代码来发送和接收数据,但是当我接收数据时却得到-1。发送不给出任何错误。

服务器代码:

struct sockaddr_in name;
char *buf;

int main(int agrc, char** argv) {

int sock, new_sd;   //sock is this socket, new_sd is connection socket
int adrlen, cnt;

name.sin_family=AF_INET;
name.sin_port=htons(6050);

sock = socket(AF_INET, SOCK_STREAM, 0);

if (sock < 0) {
    printf("\nserver socket failure ");
    printf("\nServer: ");
    exit(1);
}
printf("sockfd=%d\n",sock);
adrlen=(socklen_t)sizeof(name);
if((bind (sock,(struct sockaddr *)&name,adrlen)) < 0)
   printf("\nBind failure");
if(listen(sock, 5) < 0)
   printf("\nlisten error ");
printf("listen done\n");
while(1) {
    if( new_sd =(accept(sock,(struct sockaddr *)&name,(socklen_t*)&adrlen)) < 0) {
        printf("\nserver accept failure ");
        exit(1);
    }
    printf("new_sd=%d",new_sd);

    buf = (char *)malloc(14);
    if((recv(new_sd,(void *)buf,14,MSG_WAITALL)) < 0){
       printf("\nError receiving data ");
        exit(1);
    }
}   //end while
return 0;
}


客户代码:

char buf[14];
struct sockaddr_in name;

int main(int agrc, char** argv) {

int sock, new_sd, adrlen, cnt;
name.sin_family=AF_INET;
name.sin_port=htons(6050);

sock = socket(AF_INET, SOCK_STREAM, 0);

if (sock < 0) {
   printf("\nserver socket failure ");
   printf("\nServer: ");
    exit(1);
}

//stuff for server socket
printf("sock is %d\n",sock);
adrlen=(socklen_t)sizeof(name);


if((connect(sock,(struct sockaddr *)&name,adrlen)) < 0) {
    printf("\nclient connection failure ");
    exit(1);
}

printf("\nSuccessful connection from client 1");

strcpy(buf,"\nclientsend");

if((send(sock,(void *)buf,strlen(buf), 0)) < 0) {
    printf("\nError sending data from client 1 ");
    exit(1);
}
printf("\nExiting normally");
return 0;
}

最佳答案

可能会出现许多错误。您应该使用GetLastError()来了解更多信息。

另外,我注意到在客户端和服务器示例中,您都没有完全初始化“ sockaddr_in name”,例如,name.ai_addr保持不变。如果使用TCP(SOCK_STREAM),则需要一个地址来连接。

关于c - 套接字send()和recv()无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23800564/

10-11 21:23