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

Winsock client and server wont connect

我用winsock2写了一个客户端和服务器。服务器似乎 运行 正常,但是当我 运行 客户端时,它立即 returns "Socket operation on nonsocket" 的 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 分配给 "sock",您需要以下内容:

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

在赋值之后进行比较,而不是赋值比较的结果。这是运算符优先级的问题,== "winning" 优于 =.