QTcpSoket QTcpServer

客户端:

QNetworkProxyFactory::setUseSystemConfiguration(false);  //取消代理链接
serverIP = new QHostAddress();  
if (!serverIP->setAddress("127.0.0.1"))
QMessageBox::about(0, "提示!", "连接失败!");
connectToHost(*serverIP, 9977);  //链接服务器IP地址 ,端口号
waitForConnected(500); //最大等待500毫秒  
connect(this, SIGNAL(connected()), this, SLOT(slots_connection()));  //连接上之后,触发自定义槽函数
connect(this, SIGNAL(readyRead()), this, SLOT(slots_receiveInfo())); //有消息到来,触发自定义槽函数
connect(this, SIGNAL(disconnected()), this, SLOT(slots_disconnect()));//断开连接之后,触发自定义槽函数

 

服务端:

if (!listen(QHostAddress::Any, 9977));//监听 端口,一定要Any,否则监控不到信号的到来
QMessageBox::about(0, "info", "failure!");
connectSocket = nullptr;
userReg = nullptr;
connect(this, SIGNAL(newConnection()), this, SLOT(slots_newConnection()));  //收到 客户端信息 ,触发槽函数。

 

void TcpServer::slots_newConnection()
{
if (hasPendingConnections())
{
connectSocket = nextPendingConnection();  //获取新的 socket链接
QHostAddress clientAddr = connectSocket->peerAddress(); //获取来访IP
emit newInfo(clientAddr.toString()); 
this->connect(connectSocket, SIGNAL(readyRead()), this, SLOT(slots_receiveInfo())); //触发读写信息的槽函数
this->connect(connectSocket, SIGNAL(disconnected()), connectSocket, SLOT(deleteLater())); //断开释放连接
}

}

posted @ 2021-02-10 20:37  tonny1000  阅读(304)  评论(0)    收藏  举报