【问题标题】:why my TCP server code send a SYN/ACK on only first packet or only on the first connection?为什么我的 TCP 服务器代码仅在第一个数据包或仅在第一个连接上发送 SYN/ACK?
【发布时间】:2014-02-13 13:49:25
【问题描述】:
SOCKET sock;
SOCKET fd;
uint16 port = 18001;

void CreateSocket()
{
   struct sockaddr_in server, client;  // creating a socket address structure: structure contains ip address and port number
  WORD wVersionRequested;
WSADATA wsaData;
int len;

    printf("Initializing Winsock\n");


    wVersionRequested = MAKEWORD (2, 2);
    iResult =  WSAStartup (wVersionRequested, &wsaData);      
if (iResult != NO_ERROR)
  printf("Error at WSAStartup()\n"); 


    // create socket
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0)    {
        printf("Could not Create Socket\n");
        //return 0;
    }

    printf("Socket Created\n");




    // create socket address of the server
    memset( &server, 0, sizeof(server));
    // IPv4 - connection
    server.sin_family = AF_INET;
    // accept connections from any ip adress
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    // set port
    server.sin_port = htons(18001);


    //Binding between the socket and ip address
    if(bind (sock, (struct sockaddr *) &server, sizeof(server)) < 0)
    {
        printf("Bind failed with error code: %d", WSAGetLastError());
    }

    //Listen to incoming connections
    if(listen(sock,3) == -1){
        printf("Listen failed with error code: %d", WSAGetLastError());
    }

    printf("Server has been successfully set up - Waiting for incoming connections");

    for(;;){
        len = sizeof(client);
        fd = accept(sock, (struct sockaddr*) &client, &len);

        if (fd < 0){
            printf("Accept failed");
            close(sock);
        }
        //echo(fd);
        printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//closesocket(fd);
    }

}

服务器代码正在通过 IP 地址和端口号接受来自客户端的连接。它仅在第一次连接期间向客户端发送 SYN/ACK,第二次发送如下所示:RST / ACK(第二次正在重置)。

谁能告诉我上面的代码有什么错误??

【问题讨论】:

  • 如果您在这些调用中的任何一个中遇到错误,那么就好像您没有那样继续下去是没有意义的。
  • 你能告诉我那到底是什么吗?我想这样做三遍来启动我的客户。
  • 我能告诉你what到底是什么吗?

标签: multithreading sockets tcp ip port


【解决方案1】:

Accept multiple subsequent connections to socket

这里引用一句:“要为多个客户端提供服务,您需要避免阻塞 I/O - 即,您不能只从套接字读取并阻塞,直到数据进入。”

【讨论】:

  • 非常感谢。我尝试了非阻塞模式: iResult = ioctlsocket(sock, FIONBIO, &iMode);现在我在wireshark中遇到一个问题:第一次连接很好。在第二个连接中:SYN (Master to slave), SYN, ACK (Slave to master), ACK (Master to Slave), ACK (Slave to master) 再一次 ACK 从 master 到 slave 等等。我连续收到三到四次的确认。这是什么原因??
  • 报价不正确。如果您为每个客户端启动一个线程,则无需避免阻塞 I/O。
猜你喜欢
  • 2021-10-31
  • 2013-03-06
  • 2016-09-17
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多