gpt4 book ai didi

c - 套接字发送()和接收()不工作

转载 作者:行者123 更新时间:2023-11-30 18:13:35 26 4
gpt4 key购买 nike

我编写了一个简单的代码来send()recv()数据,但是当我recv()<时,我得到的错误为-1/em> 数据。发送没有给出任何错误。

服务器代码:

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 - 套接字发送()和接收()不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23800564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com