基本功能
详细说明请见官方文档
范例代码见GitHub:QtOtherModuleExamples
pro文件配置
使用Qt网络功能需要在pro文件增加网络库
QT += network
QTcpServer服务端建立
QTcpServer server = new QTcpServer();
connect(server,
&QTcpServer::newConnection,
this,
&MainWindow::server_New_Connect);//监听
if(!server->listen(QHostAddress::Any, 8000)) {
qDebug()<<server->errorString(); //错误信息
}
创建server对象以后首先要监听客户端的连接,通过listen函数可以开启监听,需要指定监听的ip和端口号,ip可使用QHostAddress::Any
QTcpServer当有新客户端连接时会发出QTcpServer::newConnection的信号,只需要关联到自定义的槽即可。