Qt的socket通信

service端

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    tcpServer = new QTcpServer(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_start_service_clicked()
{
    tcpServer->listen(QHostAddress::Any,1214);

    connect(tcpServer, SIGNAL(newConnection()),this, SLOT(acceptConnection()));
}

void MainWindow::acceptConnection()
{
    tcpSocket = new QTcpSocket;
    tcpSocket = tcpServer->nextPendingConnection();                //使TCPsocket=当前访问者
    connect(tcpSocket, SIGNAL(readyRead()),this, SLOT(recv_Msg()));//连接槽当有数据时进入
    qDebug("accept");
    connect(tcpSocket, SIGNAL(disconnected()),this, SLOT(clear_socket()));
}

void MainWindow::recv_Msg()
{
    QString Recv;
    Recv += tcpSocket->readAll();

    ui->textEdit_Recv->moveCursor(QTextCursor::End);
    ui->textEdit_Recv->insertPlainText(Recv);
    qDebug("recv_Msg");
    tcpSocket->write(Recv.toLatin1());
    qDebug("write");
}


void MainWindow::on_stop_service_clicked()
{
     tcpServer->close();
}
void MainWindow::clear_socket()
{
    qDebug()<< "clear_socket";
    tcpSocket->close();
}
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_start_service_clicked();
    void recv_Msg();
    void acceptConnection();
    void clear_socket();
    void on_stop_service_clicked();

private:
    Ui::MainWindow *ui;
    QTcpServer *tcpServer;

    QTcpSocket *tcpSocket;
};

#endif // MAINWINDOW_H

client端

widget.cpp

#include "widget.h"
#include "ui_widget.h"

#include <QtextStream>
#include <QDebug>
#include <QHostAddress>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket( this );
//在这里设置文本框的默认值,不要在样式里设置。否则修改了文本框值获取的还是默认的。
    ui->lineEdit_ip->setText("192.168.1.214");
    ui->lineEdit_port->setText("1214");
    ui->textEdit_send->setText("Hello World!");

    connect( tcpSocket, SIGNAL(error(int)), this, SLOT(errMsg(int)) );
    connect( ui->client_Send, SIGNAL(clicked()), this, SLOT(on_pushButton_Send_clicked(bool)) );
    connect( ui->client_Connect, SIGNAL(clicked()), this, SLOT(on_pushButton_Connect_clicked(bool)) );
    connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(recvMsg()) );

    ui->client_Send->setEnabled(false);
    ui->client_Close->setEnabled(false);

}

Widget::~Widget()
{
    delete ui;
}
void Widget::errMsg( int errNo )
{
   qWarning( "this is err %d!", errNo );

}

void Widget::on_client_Connect_clicked()
{
    QString port;
    int port_Int;

    port = ui->lineEdit_port->text();
    port_Int = port.toInt();

    tcpSocket->connectToHost(QHostAddress(ui->lineEdit_ip->text()),port_Int,QIODevice::ReadWrite);

    if (!tcpSocket->waitForConnected(2))
    {
        tcpSocket->disconnectFromHost();
        qDebug("error");
        return;
    }
    ui->client_Connect->setEnabled(false);
    ui->client_Send->setEnabled(true);
    ui->client_Close->setEnabled(true);
    qDebug("connect");
}

void Widget::on_client_Send_clicked()
{
     QString context = ui->textEdit_send->toPlainText();
//    QTextStream out(tcpSocket);
//    out << context << endl;
// 或者使用下面的 tcpSocket->write方法
    tcpSocket->write(context.toLatin1());
    qDebug("send");
}
void Widget::recvMsg()
{

    QByteArray new_data;
//    tcpSocket =new QTcpSocket;//不要再new一个出来,这样就不是原来有内容的tcpSocket
    new_data += tcpSocket->readAll();
    ui->textEdit_recv->insertPlainText(QString(new_data));

}
void Widget::on_client_Close_clicked()
{
     qDebug("disconnect");
     ui->client_Close->setEnabled(false);
     ui->client_Connect->setEnabled(true);
   //  ui->client_Send->setEnabled(false);
     tcpSocket->disconnectFromHost();
}
widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpSocket>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    //需要把这些放在槽这里声明,到public和private都触发不了。
    void on_client_Connect_clicked();
    void on_client_Send_clicked();
    void on_client_Close_clicked();
    void recvMsg();
    void errMsg( int errNo );
private:
    Ui::Widget *ui;
    QTcpSocket *tcpSocket;

};

#endif // WIDGET_H
可参考:https://wuyuans.com/2013/03/qt-socket/

简单的通信:

TCP client端

#include <QtNetwork>
QTcpSocket *client;
char *data="hello qt!";
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.21.11.66"), 6665);
client->write(data);
TCP server端

#include <QtNetwork>
QTcpServer *server;
QTcpSocket *clientConnection;
server = new QTcpServer();
server->listen(QHostAddress::Any, 6665);
connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
void acceptConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
}
void readClient()
{
    QString str = clientConnection->readAll();
    //或者下面的读取方法
    //char buf[1024];
   //clientConnection->read(buf,1024);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值