我正在尝试使用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是成功的。 我在做什么错?
tcpserver和tcpClient似乎都是非指针成员变量,您似乎没有初始化它们。 – Abhijith 2011-05-25 20:25:34
这是一个想法。我会尝试回复结果。 – OneMoreVladimir 2011-05-25 20:35:06
将两者转换为指针并使用新的QTcp *(this)进行初始化,但仍然不起作用=( – OneMoreVladimir 2011-05-25 20:41:06