Qt编程入门3 网络

来源:互联网 发布:wampserver for mac 编辑:程序博客网 时间:2024/05/16 18:28

1,获取本机网络信息

获取主机信息
QString hostname = QHostInfo::localHostName(); 
qDebug() << hostname; QHostInfo hostinfo = QHostInfo::fromName(hostname); QList<QHostAddress>listaddr = hostinfo.addresses(); 
for (int i=0; i<listaddr.size();i++)
  {
qDebug() << listaddr.at(i); 
}


2,获得与网络接口相关信息

QList<QNetworkInterface>list = QNetworkInterface::allInterfaces(); 
for (int i=0; i<list.count(); i++) 
{
QNetworkInterface face = list.at(i);QList<QNetworkAddressEntry>entrylist = face.addressEntries(); 
for (int j=0; j<entrylist.count(); j++)
{
QNetworkAddressEntry entry = entrylist.at(j);
qDebug() << "ip:" << entry.ip();
}
  }


3,基于UDP网络编程

服务器端
创建套接字
serverSocket = new udpsocket(this);  


绑定套接字
serverSocket->bind(QHostAddress::Any, 8040);


设定当有数据可以接收调用的槽函数
connect(this, SIGNAL(readyRead()), this, SLOT(recvdata())); 


数据接收槽函数实现
protected slots: 
void recvdata() 
{
while (this->hasPendingDatagrams()) 
{
QByteArray datagram;
datagram.resize(this->pendingDatagramSize());
this->readDatagram(datagram.data(), datagram.size());QString s = datagram.data();QMessageBox::information(NULL, "msg", s);;
emit updatemsg(s);
}
}


客户端
创建套接字
QUdpSocket *socket = new QUdpSocket(this);


发送数据
QString s = “hello"; 
socket->writeDatagram(s.toLatin1(), s.length(), QHostAddress::Broadcast, 8040);


4,基于TCP网络编程

服务器端
QTcpSever创建监听套接字
tcpServer::tcpServer(QObject *parent, int port): QTcpServer(parent) 
{
listen(QHostAddress::Any, port); 
}


重写QTcpSever ::incomingConnection(int)方法,该函数当有新的连接时会被自动调用
void tcpServer::incomingConnection(int sock)
 {
tcpSocket *tcpsock = new tcpSocket(this);
tcpsock->setSocketDescriptor(sock);
 }


创建QTcpSocket连接套接字
tcpSocket::tcpSocket(QObject *parent): QTcpSocket(parent) {
connect(this, SIGNAL(readyRead()), this, SLOT(dataRecv()));
}
void tcpSocket::dataRecv()
{ while (bytesAvailable() > 0) {
int len = bytesAvailable(); 
char buf[1024] = {0};
read(buf, len); 
QMessageBox::information(NULL, "msg", buf); 

}


QIODevice是所有Qt I/O设备的基类, readyRead() -- 当data有新数据准备好时发出信号。例如,新数据通过network到达或者有数据附加到了你正在读取的文件之后;
bytesAvailable()-- 确定当前可读数据的字节数,当对非同步设备例如QTcpSocket(此类设备的数据段到达的时间是随机的)编程时,常与readyRead()信号联用。


客户端
创建套接字
QTcpSocket *socket = new QTcpSocket(this); 


连接服务器
socket->connectToHost(QHostAddress("127.0.0.1"), 8010); 

发送消息
QString s = "hello server";
socket->write(s.toLatin1(), s.length());

博文索引  持续更新中。。。