2011-05-25 90 views
0

我正在尝试使用QTcpSocket和QTcpServer编写聊天。 我的代码QTcpSocket连接

客户

ChatClient::ChatClient(QObject *parent) 
    : QObject(parent) { 
    connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), 
      this, SLOT(error(QAbstractSocket::SocketError))); 
    connect(&tcpSocket, SIGNAL(connected()), 
      this, SLOT(requestForID())); 
    connect(&tcpSocket, SIGNAL(readyRead()), 
      this, SLOT(receiveMessage())); 
    tcpSocket.connectToHost(QHostAddress::LocalHost, PORT); 
} 

void ChatClient::requestForID() { 
    qDebug() << "Connected, requesting for ID"; 
    QByteArray segment; 
    QDataStream out(segment); 
    out.setVersion(QDataStream::Qt_4_7); 
    out << (quint16)0 << ID; 
    out.device()->seek(0); 
    out << (quint16)(segment.size() - sizeof(quint16)); 
    tcpSocket.write(segment); 
} 

void ChatClient::error(QAbstractSocket::SocketError error) { 
    qDebug() << "Socket error" << error; 
} 

服务器

ChatServer::ChatServer(QObject *parent) 
    : QObject(parent) { 
    if (!tcpServer.listen(QHostAddress::LocalHost, PORT)) { 
     qDebug() << "Unable to start the server" 
       << tcpServer.errorString(); 
    } 
    connect(&tcpServer, SIGNAL(newConnection()), 
      this, SLOT(processConnection())); 
} 

客户端插座几件永远不会被连接。错误永远不会被打印。 PORT = 6178. Runnig KUbuntu。从bash ping到localhost是成功的。 我在做什么错?

+1

tcpserver和tcpClient似乎都是非指针成员变量,您似乎没有初始化它们。 – Abhijith 2011-05-25 20:25:34

+0

这是一个想法。我会尝试回复结果。 – OneMoreVladimir 2011-05-25 20:35:06

+0

将两者转换为指针并使用新的QTcp *(this)进行初始化,但仍然不起作用=( – OneMoreVladimir 2011-05-25 20:41:06

回答

1

我在代码中看不到任何错误,您确定您的Qt和“网络”工作正常吗? Qt应该发出一个错误,但至少你的代码片段在这里看起来是正确的。也许你的代码永远不会被调用,向方法添加一些调试消息。

最后,您可以构建Qt网络示例并测试它是否可以在您的机器上运行。如果您没有这些示例,请看这里:http://doc.qt.io/qt-5/examples-network.html(用于TCP的Fortune服务器/客户端)

+0

感谢您回复Xander。我已经构建了tripplanner和tripserver示例(来自编程Qt GUI 4)并且它们可以工作,唯一的区别是tripserver正在使用QTcpSocket而不是QTcpServer。根据http://doc.qt.nokia.com/4.7/network-fortuneserver.html我也没有看到任何错误。 – OneMoreVladimir 2011-05-25 20:26:48