赞
踩
网络编程包括TCP和UDP TCP的编程需要用到两个类:QTcpServer和QTcpSocket 本节将完成一个TCP服务器和一个客户端 首先我们需要完成布局
在pro文件下添加QT += core gui network
,.h文件下包含头文件#include <QTcpServer>,#include <QTcpSocket>
,并且创建对象
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
tcpServer = new QTcpServer(this);
tcpSocket = new QTcpSocket(this);
tcpServer->listen(QHostAddress::Any,ui->NumEdit->text().toUInt());
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
void TCPServer::readyRead_Slot()
{
QString buf;
buf = tcpSocket->readAll();
ui->ReceveEdit->appendPlainText(buf);
}
void TCPServer::on_Open_clicked() { tcpServer->listen(QHostAddress::Any,ui->NumEdit->text().toUInt()); } void TCPServer::on_Close_clicked() { tcpServer->close(); } void TCPServer::on_Close_2_clicked() { tcpSocket->write(ui->SendEdit->text().toLocal8Bit().data()); }
.h文件中添加头文件#include <QTcpSocket>
,对象 QTcpSocket *tcpSocekt;
添加槽函数
private slots:
void on_OpenBT_clicked();
void connected_Slot();
void readyRead_Slot();
void on_CloseBT_clicked();
void on_SendBT_clicked();
.cpp文件中添加功能
void Widget::on_OpenBT_clicked() { tcpSocekt->connectToHost(ui->IPEdit->text(),ui->NumEdit->text().toUInt()); connect(tcpSocekt,SIGNAL(connected()),this,SLOT()); } void Widget::connected_Slot() { connect(tcpSocekt,SIGNAL(connected(readyRead())),this,SLOT()); } void Widget::readyRead_Slot() { ui->ReceEdit->appendPlainText(tcpSocekt->readAll()); } void Widget::on_CloseBT_clicked() { tcpSocekt->close(); } void Widget::on_SendBT_clicked() { tcpSocekt->write(ui->SendEdit->text().toLocal8Bit()); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。