C++网络编程


782 浏览 5 years, 7 months

2.4 因特网客户端2

版权声明: 转载请注明出处 http://www.codingsoho.com/

本节主要提高客户端的灵活性,可以使客户机发送想要的任何消息

代码如下,循环接收用户输入,通过send函数将数据发送到服务器,如果消息为servquit或者quit,那么关闭套接字

cin的getline()函数本质上时告诉它取得数据,并存储到消息缓冲区中,直到用户按下Enter键,或者字符达到128个。完成这些操作之后,就可以发送数据了。

    char message[128] = "Hello Internet!";
    bool done = false;
    cout << "Type data to send now:" << endl;
    while( !done )
    {
        // get data to send
        cin.getline( message, 128 );
        // send data
        err = send( sock, message, strlen( message ) + 1, 0 );
        if( err == -1 )
        {
            cout << "Socket sending error!" << endl;
            return 0;
        }
        if( strcmp( message, "servquit" ) == 0 || 
            strcmp( message, "quit" ) == 0 )
        {
            done = true;
        }
    }