"); //-->
服务器代码:
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
private:
Ui::Widget *ui;
private slots:
void on_openBt_clicked();
void newConnection_Slot();
void readyRead_Slot();
void on_closeBt_clicked();
void on_sendBt_clicked();
};
#endif // WIDGET_Hwidget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
tcpSocket = new QTcpSocket(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
}
void Widget::newConnection_Slot()
{
tcpSocket=tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget::readyRead_Slot()
{
QString buf;
buf=tcpSocket->readAll();
ui->recvEdit->appendPlainText(buf);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_openBt_clicked()
{
tcpServer->listen(QHostAddress::Any,ui->portEdit->text().toUInt());
}
void Widget::on_closeBt_clicked()
{
tcpServer->close();
}
void Widget::on_sendBt_clicked()
{
tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}客户端代码:
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();
QTcpSocket *tcpSocket;
private slots:
void on_openBt_clicked();
void connected_Slot();
void readyRead_Slot();
void on_closeBt_clicked();
void on_sendBt_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_Hwidget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpSocket=new QTcpSocket(this);
}
void Widget::connected_Slot()
{
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget::readyRead_Slot()
{
ui->recvtEdit->appendPlainText(tcpSocket->readAll());
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_openBt_clicked()
{
tcpSocket->connectToHost(ui->ipEdit->text(),ui->portEdit->text().toUInt());
connect(tcpSocket,SIGNAL(connected()),this,SLOT(connected_Slot()));
}
void Widget::on_closeBt_clicked()
{
tcpSocket->close();
}
void Widget::on_sendBt_clicked()
{
tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}运行效果图;

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。