C ++网络程序运行,但没有输出

时间:2013-01-14 22:14:05

标签: c++ network-programming

我的简单程序通过编译器没有错误并且运行正常,但是在有人连接之前它也不会给出输出。我做了很多研究和编辑,但无法弄明白。我怎样才能让一个人连接?任何有助于此工作的帮助将不胜感激。提前致谢!!!代码如下。

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>

char msg[20];

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Made it to main!";

    int listener_d = socket(PF_INET, SOCK_STREAM, 0);

    struct sockaddr_in name;
    name.sin_family = PF_INET;
    name.sin_port = (in_port_t)htons(30000);
    name.sin_addr.s_addr = INADDR_ANY;
    if(bind (listener_d, (struct sockaddr *) &name, sizeof(name)) == -1)
    {
        cout << "Can't bind the port!";
    }
    else
    {
        cout << "The port has been bound.";
    }

    listen(listener_d, 10);
    cout << "Waiting for connection...";

    while(1)
    {
        struct sockaddr_storage client_addr;
        unsigned int address_size = sizeof(client_addr);
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &address_size);
        cin >> msg;

        send(connect_d, msg, strlen(msg), 0);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

也许你应该尝试刷新输出。

std::cout << "Waiting for connection..." << std::flush;