Qt下TCP编程

一、服务器

1、声明一个QTcpServer对象

QTcpServer* serverListener;

2、new出对象

this->serverListener = new QTcpServer();

3、服务器监听

QHostAddress ipAddress(“192.168.1.1”);

quint16 ipPort = 8080;

serverListener->listen(ipAddress,ipPort);

4、声明一个QList对象用于存客户端

QList<QTcpSocket*> clientList;

5、连接信号与槽

QObject::connect(this->serverListener,SIGNAL(newConnection()),this,SLOT(newConnection()));//newConnection是自定义槽函数,用于管理clientList列表

6、实现newConnection函数,保存客户端至clientList

void TcpServer::newConnection()

{

  QTcpSocket* serverClient = this->serverListener->nextPendingConnection();//new出客户端对象

  this->clientList.append(serverClient);//保存

  QObject::connect(serverClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//当此客户端有数据时在自定义rcvData函数里接收

  QObject::connect(serverClient,SIGNAL(disconnected()),this,SLOT(removeClient()));//当此客户端断开连接时,会发出disconnected信号,在自定义removeClient里去除客户端

}

7、实现removeClient函数,去除客户端

void TcpServer::removeClient()

{

  for(int i=0;i<this->clientList.length();i++)

  {

  if(clientList.at(i)->socketDescriptor() == -1)//用于判断当前客户端是否有效

    clientList.removeAt(i);

  }

}

8、实现rcvData函数,接收数据

void TcpServer::rcvData()

{ 

  QByteArray ba;
  for(int i=0;i<this->clientList.length();i++)
  {
    if(clientList.at(i)->atEnd() == true)
      continue;
    ba = clientList.at(i)->readAll();

    //
  }

}

9、发送数据

clientList.at(n)->write(QByteArray ba);

10、停止

serverListener->close();

二、客户端

1、声明一个QTcpSocket对象

QTcpSocket* tcpClient;

2、new出对象

this->tcpClient = new QTcpSocket();

3、连接服务器,连接信号与槽

tcpClient->connectToHost("192.168.1.1","8080");

QObject::connect(this->tcpClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//rcvData是自定义接收槽函数

4、实现rcvData函数,接收数据

void TcpClient::rcvData()

{

  QByteArray ba = tcpClient->readAll();

}

5、发送数据

tcpClient->write(QByteArray ba);

6、关闭

tcpClient->close();

ps:软件开发流程

ps:

在一次编写tcp服务器过程中,用tcp来listen电脑的ip,发现总是listen没有报错,但是用小黄人总是连接不上。

原来电脑有多个ip,比如局域网ip、127那个默认ip、虚拟机ip,电脑会有一个ip的优先级排序,如果上面listen的ip不是电脑优先级最高那个,就会出现这样的问题。

解决:1、把其他ip禁掉  2、修改电脑ip优先级

原文地址:https://www.cnblogs.com/judes/p/6900127.html