一、总结#
TCP
就像打电话,安全,不会丢包
Linux TCP
通信
Qt TCP
通信
二、服务器端#
TCP
服务器端有两个套接字,一个是监听套接字,一个是通信套接字
tcpServer = nullptr; // 服务监听套接字
tcpSocket = nullptr; // 通信套接字
// 创建tcp服务监听套接字
tcpServer = new QTcpServer(this);
// tcp服务开启监听(bind端口号并开启监听)
tcpServer->listen(QHostAddress::Any, 8008);
// 绑定连接成功信号
connect(tcpServer, &QTcpServer::newConnection,[=](){
// 获取通信套接字
tcpSocket = tcpServer->nextPendingConnection();
// 获取客户端 IP 和 端口
QString ip = tcpSocket->peerAddress().toString();
quint16 port = tcpSocket->peerPort();
QString msg = QString("[%1:%2] 连接成功").arg(ip).arg(port);
ui->textEditRead->append(msg);
// 绑定通信套接字读取信息
connect(tcpSocket, &QTcpSocket::readyRead, [=](){
QByteArray msg = tcpSocket->readAll();
ui->textEditRead->append(msg);
});
});
if(nullptr == tcpSocket){
return;
}
QString msg = ui->textEditWrite->toPlainText();
tcpSocket->write(msg.toUtf8());
if(nullptr == tcpSocket){
return;
}
// 主动断开客户端连接
tcpSocket->disconnectFromHost();
// 关闭通信套接字
tcpSocket->close();
delete tcpSocket;
tcpSocket = nullptr;
三、客户端#
tcpSocket = new QTcpSocket(this);
// 与服务器连接成功后
connect(tcpSocket, &QTcpSocket::connected,[=](){
ui->textEditRead->setText(QString("和服务器连接成功"));
});
// 接收服务器端的消息
connect(tcpSocket, &QTcpSocket::readyRead, [=](){
QByteArray str = tcpSocket->readAll();
ui->textEditRead->append(str);
});
// 主动和服务器建立连接
QString ip = ui->lineEditIP->text();
int port = ui->lineEditPort->text().toInt();
tcpSocket->connectToHost(QHostAddress(ip), port);
if(false == tcpSocket->isOpen()){
return;
}
QString str = ui->textEditWrite->toPlainText();
tcpSocket->write(str.toUtf8());
tcpSocket->disconnectFromHost();
tcpSocket->close();