gpt4 book ai didi

c - Winsock 客户端和服务器无法连接

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:05 25 4
gpt4 key购买 nike

我已经使用 winsock2 编写了客户端和服务器。服务器似乎运行良好,但当我运行客户端时,它立即返回“非套接字上的套接字操作”的 10038 错误代码。不确定为什么这样做会创建套接字并返回错误。

这是客户端的代码,它在连接函数调用时失败:

#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int *argc, char **argv){
struct sockaddr_in server, client;
char server_reply[2000];
WSADATA wsa;
int result = WSAStartup(MAKEWORD(2,2),&wsa);
SOCKET sock, newSock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET)){
printf("Failed to create socketwith error code : %d" , WSAGetLastError());
}
else{
printf("Socket created\n");
}
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8080);
if((newSock = connect(sock , (struct sockaddr *)&server , sizeof(server)) == INVALID_SOCKET )){
printf("connect failed with error code : %d" , WSAGetLastError());
}
else{
printf("connected");
}
closesocket(socket);
WSACleanup();
return 0;

}

我认为有效的服务器代码:

#include<io.h>
#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char message[54];


printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8080 );

//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
return 1;
}

puts("Bind done");

//Listen to incoming connections
listen(s , 3);

//Accept and incoming connection
puts("Waiting for incoming connections...");

c = sizeof(struct sockaddr_in);
while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
{
recv(s, message, 2000, 0);
printf(message);

}

if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return 1;
}


closesocket(s);
WSACleanup();

return 0;
}

最佳答案

你把括号设置错了:

if ((sock = socket(AF_INET, SOCK_STREAM, 0)  == INVALID_SOCKET))

将 0 分配给“ socks ”,您需要以下内容:

if ((sock = socket(AF_INET, SOCK_STREAM, 0))  == INVALID_SOCKET)

在赋值后进行比较,而不是赋值比较的结果。这是运算符优先级的问题,==“胜过”=

关于c - Winsock 客户端和服务器无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51085554/

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