客户端终端

时间:2017-09-21 19:19:39

标签: tcp server winsock winsock2

我创建了一个简单的TCP服务器,它监听8080端口,一旦建立连接就会向客户端发送消息。这是代码。

#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996) 

int main(int argc, char* argv[]) {
    WSADATA wsa;
    SOCKET s, new_socket;
    int c;
    int ret;
    struct sockaddr_in server, client;
    char* message = "Thank you for connecting to us but i got to go\n";

    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
        printf("Failed to initialize Winsock : %d", WSAGetLastError());
        return 1;
    }



    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s == INVALID_SOCKET) {
        printf("Error creating socket : %d", WSAGetLastError());

    }


    server.sin_family = AF_INET;
    server.sin_port = htons(8080);
    server.sin_addr.s_addr = INADDR_ANY;


    if (bind(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Error binding socket : %d\n", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    listen(s, 3);

    puts("Listening for incoming connection\n");
    c = sizeof(struct sockaddr_in);
    while (new_socket = accept(s, (struct sockaddr*)&client, &c) != INVALID_SOCKET) {
        puts("Connection established\n");
        send(new_socket, message, strlen(message), 0);
    }

    if (new_socket == INVALID_SOCKET) {
        printf("Connection failed : %d", WSAGetLastError());
        return 1;
    }

    closesocket(s);
    WSACleanup();


    return 0;

}

当我运行它时,服务器运行正常。我打开另一个终端并打开telnet并尝试连接到8080端口上的服务器。这是客户端终端。

Welcome to Microsoft Telnet Client

Escape Character is 'CTRL+]'

Microsoft Telnet> open localhost 8080
Connecting To localhost...

这是服务器端。

Listening for incoming connection

Connection established

但即使在服务器声明已建立连接之后,客户端仍保持“正在连接到本地主机”。我发送消息“感谢您连接我们,但我必须去\ n”,但它没有显示在客户端。什么可能是错的?

1 个答案:

答案 0 :(得分:-1)

看来,这是一个愚蠢的错误。

@Thusitha

由于我在初始化while (new_socket = accept(s, (struct sockaddr*)&client, &c) != INVALID_SOCKET) 后没有在new_socket = accept(s,(struct sockaddr *)&amp; client,&amp; c上放置另一个括号,因此在new_socket上应用了不等式函数返回。

正确的语法是

accept