2 freedom wings5 freedom_wings5 于 2016.03.05 12:05 提问

c++的socket编程,无客户端连接accept却不阻塞,直接返回了,怎么解决

以下是服务端的代码:

 #include "stdafx.h"
#include "winsock2.h"
#include "iostream"
#pragma comment (lib,"ws2_32")

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    WSADATA wsadata;
    WSAStartup(MAKEWORD(2, 2), &wsadata);
    cout << "开始创建套接字\n";
    SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in  saddrin;

    saddrin.sin_addr.S_un.S_addr = inet_addr("INADDR_ANY");
    saddrin.sin_port = htons(9100);

    cout << "开始绑定\n";
    bind(s, (sockaddr *)&saddrin, sizeof(saddrin));

    cout << "开始监听\n";
    listen(s, SOMAXCONN);



    struct sockaddr_in sClient;
    int num = sizeof(sClient);
    SOCKET client=  accept(s, (sockaddr *)&sClient, &num);
    if (client)
    {
        cout << "已接受来自客户端的连接\n";
        cout << sClient.sin_port<<'\n';

        cout<< inet_ntoa(sClient.sin_addr)<<'\n';

        char msg[MAXBYTE] = { 0 };

        recv(client, msg, sizeof(msg), 0);
        cout << msg;


        strcpy_s(msg, "this is a reply for the test\n");
        send(client, msg, strlen(msg) + sizeof(char), 0);
        cout << "已发送消息\n";


    }
    else
    {
        cout << "无客户端的连接";
    }
    system("PAUSE");
    return 0;
}


运行结果如下:
图片说明

启动了服务端,客户端都没启动,就直接执行完返回了,accept那里不是应该阻塞,等待客户端的连接的吗?即使同时启动客户端和服务端也是这样的结果,请问应该怎么解决?

4个回答

WinsenJiansbomber
WinsenJiansbomber   2016.03.05 13:04
已采纳

细看了一下你的输出,程序已经收到请求,所accept接收请求后继续运行了。

WinsenJiansbomber
WinsenJiansbomber   2016.03.05 12:49

应该设置同步选项啊,异步执行当然一下就过去了。

WinsenJiansbomber
WinsenJiansbomber   2016.03.05 12:57

摘一段我写的代码:

    cout << "#3 bind a Socket" << endl;
    sockaddr_in sai;
    sai.sin_family = AF_INET;
    sai.sin_addr.s_addr = inet_addr(HOST);
    sai.sin_port = htons(PORT);
    //sai.sin_zero = what?
    if ( bind( skt, (SOCKADDR*)&sai, sizeof(sai) ) == SOCKET_ERROR){
        cout << "Binding failed:" << endl;
        cout << "Error #" << WSAGetLastError() << endl;
    }

tgj1202
tgj1202   2016.03.05 16:01

从打印来看,你是收到消息了

Csdn user default icon
上传中...
上传图片
插入图片