C ++ Socket Connection自动建立?

时间:2013-05-21 15:46:37

标签: c++ linux sockets

我目前正在编写一个C ++模块,它创建一个套接字服务器线程,每隔1ms轮询一次accept()函数。我有一个测试模块,欺骗一个也在运行的客户端连接。测试模块启动服务器线程的创建。创建线程并验证其运行后,客户端将运行connect()命令作为测试。我的代码声明已建立连接,在connect命令上返回0。但是,在我的服务器线程中运行的accept()永远不会收到连接。

服务器必须接受任何IP:50000,并且客户端未绑定,但已将127.0.0.1:50000设置为其目标。我的Linux环境是否自动接受此连接?

以下是我服务器套接字的代码:

int nSocket;
int nOn = 1;
int nControl;
struct sockaddr_in  sServerAddress;

nSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(nSocket < 0)
{
    std::cout << "Failed to create socket\n";
}
if(setsockopt(nSocket, SOL_SOCKET, SO_REUSEADDR, &nOn, sizeof(int)) < 0)
{
    std::cout << "failed to set socket option\n";
}
nControl = fcntl(nSocket, F_GETFL);
if(fcntl(nSocket, F_SETFL, O_NONBLOCK | nControl) < 0)
{
    std::cout << "set not blocking failed\n";
}

memset(&sServerAddress, 0x00, sizeof(struct sockaddr_in));
sServerAddress.sin_family = AF_INET;
sServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
sServerAddress.sin_port = htons(mtListenPort);

if(bind(nSocket, (struct sockaddr*)&sServerAddress, sizeof(struct sockaddr_in)) < 0)
{
    std::cout << errno << "bind failed\n";
}

if(listen(nSocket, MAXPENDING) < 0)
{
    std::cout << "listen failed\n";
}

以下是我的测试客户端套接字的代码:

int nSocket;

nSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(nSocket < 0)
{
    std::cout << "Failed to create socket\n";
}

struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
inet_aton(LOCAL_HOST, &serverAddress.sin_addr);
serverAddress.sin_port = htons(LISTEN_PORT00);
char msg[] = "Hello World.";

usleep(10000);

if (connect(nSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0)
{
    std::cout << errno << "Could not connect to the server.\n";
}

usleep(10000);

if (sendto(nSocket, msg, strlen(msg), 0, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0)
{
    std::cout << errno << "Could not send data to the server.\n";
}

这是运行接受代码的线程的一小部分。

while(mbListening)
{
    nMessengerSocket = accept(mnSocket, (struct sockaddr*)&sClientAddr, &tClientAddrLength);
    if(nMessengerSocket >= 0)
    {
        std::cout << "Accepted connection from " << inet_ntoa(sClientAddr.sin_addr) << std::endl;
        mnConnections++;
        mbListening = false;
    }
    mThreadRunningTime++;
    usleep(1000);
}

2 个答案:

答案 0 :(得分:2)

在致电tClientAddrLength之前,请确保sizeof sClientAddr已初始化为accept()。这是一个常见的错误。

不要默默地忽略错误。检查errno中的错误代码,因为它会告诉您出了什么问题。

答案 1 :(得分:1)

您使用的是sendto吗?那是UDP ...使用send

另外,检查端口是否空闲:

telnet localhost 50000

netstat -a