socket通信之传送数据

操作步骤

QTcpServer的基本操作

1、调用 listen 监听端口。
2、连接信号 newConnection,在槽函数里调用 nextPendingConnection 获取连接进来的 socket。

QTcpSocket的基本能操作

1、调用 connectToHost 连接服务器。
2、调用 waitForConnected 判断是否连接成功。
3、连接信号 readyRead 槽函数,异步读取数据。
4、调用 waitForReadyRead,阻塞读取数据。

服务器端

  1. 新建一个服务器端工程,在 .pro 填入
	QT += network

引入头文件

	#include<QtNetwork/QtNetwork>
  1. mainwindows.h 文件中加入成员
public:
    void init();
private slots:
    void sendMessage(); //发送消息
    void onReciveData();  //接收数据
    void newListen(); //建立tcp监听事件
    void acceptConnection(); //接收客户端连接
    void showError(QAbstractSocket::SocketError); //错误输出
private:
    QTcpSocket *tcpSocket;
    QTcpServer *tcpServer;
   // QTimer *timer;
  1. 函数的定义
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();

    setWindowTitle(QString::fromLocal8Bit("Server"));
    connect(ui->sendBtn,SIGNAL(clicked(bool)),SLOT(sendMessage()));
}

构造函数中,调用 init() 函数,当点击了发送按钮就会产生一个槽函数 sendMessage,然后直接调用这个槽函数。

void MainWindow::init()
{
   // timer = new QTimer;

    tcpServer = new QTcpServer;
    tcpSocket = new QTcpSocket;
    newListen();
    connect(tcpServer,SIGNAL(newConnection()),SLOT(acceptConnection()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),SLOT(showError(QAbstractSocket::SocketError)));
}

新建一个 QTcpServer 类的对象,和 QTcpSocket 类的对象。调用 newlisten() 监听服务器的 socket 请求函数,有新的连接的时候,调用 acceptConnection() 函数,失败的话调用 showError()。

void MainWindow::newListen()
{
    if(!tcpServer->listen(QHostAddress::Any,6666))
    {
        qDebug()<<tcpServer->errorString();

        tcpServer->close();
    }
}

QHostAddress::Any4 双 any-address 栈,与该地址绑定的 socket 将侦听 IPv4,6666 端口。

void MainWindow::acceptConnection()
{
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket,SIGNAL(readyRead()),SLOT(onReciveData()));
}

连接成功后,连接信号 readyRead(),调用 onReciveData()。

void MainWindow::sendMessage()  //发送数据
{
    QString textEdit = ui->lineEdit->text();
    QString strData =QString::fromLocal8Bit("Time: ") + QTime::currentTime().toString() + "\n" + textEdit.toLocal8Bit() + "\n";
    QByteArray sendMessage = strData.toLocal8Bit();
    mChat += ("Send " + sendMessage);
    ui->textEdit->setText(mChat);
    tcpSocket->write(sendMessage);
}

void MainWindow::onReciveData()  //读取数据
{
    QString data = tcpSocket->readAll();
    qDebug()<<data;
    mChat +=("Recv " + data);
    ui->textEdit->setText(mChat);
}

发送数据,获取编辑框中的字符串,发送。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值