套接字编程c ++和python:客户端将第二条消息发送到服务器后,客户端服务器聊天通信中断。为什么?

时间:2017-05-05 22:09:37

标签: python c++ sockets chat

服务器在python中运行代码。客户端正在用C ++运行代码。服务器开始连接到正常工作的服务器,它接受用户输入并将第一条消息发送到服务器(这发生在while循环内)。服务器发送客户端消息并从服务器上的用户获取输入并将其发送到客户端。客户端显示服务器消息。它接收来自用户的输入并尝试将其发送到服务器,但服务器未显示任何内容。它看起来仍在等待客户的响应。没有显示错误。我是socketing编程的新手,我已经研究过类似的实现,它们可以保证工作,但到目前为止还没有用。如果我从客户端删除while循环它按预期工作。消息被发送到服务器并且客户端程序终止,但聊天的目的是持续通信,直到其中一方不关闭由条件处理的连接。任何帮助将不胜感激!

python中的服务器端循环:

while 1:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(4096)
    print sentence
    serverSentence = raw_input('Me >: ')
    denial = 'The Connection was ended by the server.Bye!'
    if serverSentence == '\quit':
        connectionSocket.send(denial)
        connectionSocket.close()
    else:
        fullResponse = 'Server > ' + serverSentence
        connectionSocket.send(fullResponse)

C ++中的客户端循环:

while(1)
    {
        cout << "Me >";
        string data;
        getline(cin, data);
        name.append(data);  

        memset(&msg, 0, sizeof(msg));//clear the buffer
        strcpy(msg, name.c_str());
        if(data == "\\quit")
        {\
            send(clientSd, (char*)&msg, strlen(msg), 0);
            break;
        }
        bytesWritten += send(clientSd, (char*)&msg, strlen(msg), 0);

        memset(&msg, 0, sizeof(msg));//clear the buffer
        bytesRead += recv(clientSd, (char*)&msg, sizeof(msg), 0);
        /*if(strcmp(msg, "quit"))
        {
            cout << "Server has quit the session" << endl;
            break;
        }*/
        cout<< msg << endl;
    }

    close(clientSd);
    cout << "The client has closed the connection. Bye!" << endl;

0 个答案:

没有答案