Qt websocket 服务端和客户端通信

注意事项:

Qt版本:5.3以上。

添加模块:

客户端实现

客户端.ui界面:

.h文件

#ifndef WEBSOCKETCLIENT_H
#define WEBSOCKETCLIENT_H

#include <QtWidgets/QDialog>
#include "ui_WebsocketClient.h"
#include <QWebSocket>
class WebsocketClient : public QDialog
{
	Q_OBJECT

public:
	WebsocketClient(QWidget *parent = 0);
	~WebsocketClient();


Q_SIGNALS:
	void closed();

	private Q_SLOTS:
	void connectToServer();
	void onTextMessageReceived(const QString &message);
	void closeConnection();

	public slots:
	void stopClicked();
	void onconnected();
	void onSendButtonClicked();
	void onCleanButtonClicked();

private:
	Ui::WebsocketClientClass ui;
	QUrl m_url;
	QWebSocket m_websocket;
	bool m_debug;
	QDateTime *current_date_time;
};

#endif // WEBSOCKETCLIENT_H

.cpp文件:

#include "WebsocketClient.h"

WebsocketClient::WebsocketClient(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	connect(ui.linkbutton, SIGNAL(clicked(bool)), this, SLOT(connectToServer()));
	connect(ui.disconnectbutton, SIGNAL(clicked(bool)), this, SLOT(stopClicked()));
	connect(ui.sendbutton, SIGNAL(clicked(bool)), this, SLOT(onSendButtonClicked()));
	connect(ui.cleanButton, SIGNAL(clicked(bool)), this, SLOT(onCleanButtonClicked()));
	connect(&m_websocket, SIGNAL(connected()), this, SLOT(onconnected()));
	connect(&m_websocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
	connect(&m_websocket, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString)));

}

WebsocketClient::~WebsocketClient()
{
	m_websocket.errorString();
	m_websocket.close();
}
//断开连接操作
void WebsocketClient::closeConnection() {
	ui.linkbutton->setEnabled(true);
	ui.disconnectbutton->setEnabled(false);
	ui.sendmessagetextedit->setEnabled(false);
	ui.sendbutton->setEnabled(false);
	ui.receivemessageTextEdit->setEnabled(false);
	ui.cleanButton->setEnabled(false);
	ui.statusLabel->setText(tr("disconnected"));
}
//连接服务器
void WebsocketClient::connectToServer()
{
	QString path = QString("ws://%1:%2").arg(ui.iplineedit->text()).arg(ui.portspinbox->text());
	QUrl url = QUrl(path);
	m_websocket.open(url);
}
//连接上之后
void WebsocketClient::onconnected() {
	qDebug() << "hello word!";
	ui.statusLabel->setText(tr("connected"));
	ui.linkbutton->setEnabled(false);
	ui.disconnectbutton->setEnabled(true);
	ui.sendmessagetextedit->setEnabled(true);
	ui.sendbutton->setEnabled(true);
	ui.receivemessageTextEdit->setEnabled(true);
	ui.cleanButton->setEnabled(true);
}
//收到消息
void WebsocketClient::onTextMessageReceived(const QString &message)
{
	QString time = current_date_time->currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd");
	ui.receivemessageTextEdit->append(time + "\n" + message);
}
//断开
void WebsocketClient::stopClicked()
{
	m_websocket.close();
}
//发送消息
void WebsocketClient::onSendButtonClicked()
{
	QString msg = ui.sendmessagetextedit->document()->toPlainText();
	m_websocket.sendTextMessage(msg);
}
//清除内容
void WebsocketClient::onCleanButtonClicked()
{
	ui.receivemessageTextEdit->clear();
}

服务端实现 

服务端.ui界面文件:

.h文件 

#ifndef SERVERDIALOG_H
#define SERVERDIALOG_H

#include <QtWidgets/QDialog>
#include "ui_serverdialog.h"

#include <QDialog>
#include <QLineEdit>
#include <QTextEdit>
#include <QListWidget>
#include <QList>
#include <QListWidgetItem>
#include <QTableWidget>
#include <QPushButton>
#include <QSpinBox>
#include <QTime>
#include <QWebSocketServer>
#include <QWebSocket>
class ServerDialog : public QDialog
{
	Q_OBJECT

public:
	ServerDialog(QWidget *parent = 0);
	~ServerDialog();

public slots:
	void onStartButtonClick();
	void onStopButtonClick();
	void onSendButtonClick();
	void onCleanButtonClick();
Q_SIGNALS:
	void closed();
	private Q_SLOTS:
	void onNewConnection();
	void processTextMessage(QString message);
	void socketDisconnected();

private:
	Ui::ServerDialogClass ui;

	QWebSocketServer * m_WebSocketServer;
	QList<QWebSocket *> m_clients;
	bool m_debug;
	QWebSocket *pSocket;
	QDateTime *current_date_time;

};

#endif // SERVERDIALOG_H

 .cpp文件:

#include "serverdialog.h"
#include <QHostAddress>
ServerDialog::ServerDialog(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	m_WebSocketServer = new QWebSocketServer("server", QWebSocketServer::NonSecureMode);
	connect(m_WebSocketServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
	connect(ui.startButton, SIGNAL(clicked(bool)), this, SLOT(onStartButtonClick()));
	connect(ui.stopButton, SIGNAL(clicked(bool)), this, SLOT(onStopButtonClick()));
	connect(ui.cleanButton, SIGNAL(clicked(bool)), this, SLOT(onCleanButtonClick()));
	connect(ui.sendButton, SIGNAL(clicked(bool)), this, SLOT(onSendButtonClick()));
}

ServerDialog::~ServerDialog()
{

}

void ServerDialog::onStartButtonClick() {
	int i_port = ui.monitorSpinBox->text().toInt();
	m_WebSocketServer->listen(QHostAddress::Any, i_port);
	ui.startButton->setEnabled(false);
	ui.stopButton->setEnabled(true);
}
void ServerDialog::onStopButtonClick() {
	ui.startButton->setEnabled(true);
	ui.stopButton->setEnabled(false);
	m_WebSocketServer->close();
}
void ServerDialog::onSendButtonClick() {
	QString msg = ui.sendTextedit->document()->toPlainText();
	for (int i=0;i<m_clients.size();i++)
	{
		m_clients.at(i)->sendTextMessage(msg);
	}
}
void ServerDialog::onCleanButtonClick() {
	ui.receiveTextEdit->clear();
}
//连接上之后
void ServerDialog::onNewConnection() {

	ui.startButton->setEnabled(false);
	ui.stopButton->setEnabled(true);
	ui.sendTextedit->setEnabled(true);
	ui.sendButton->setEnabled(true);
	ui.cleanButton->setEnabled(true);

	pSocket = m_WebSocketServer->nextPendingConnection();

	connect(pSocket, SIGNAL(textMessageReceived(QString)), this, SLOT(processTextMessage(QString)));
	connect(pSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));

	QString item = pSocket->peerAddress().toString();
	ui.linkclientListWidget->addItem(item);
	m_clients << pSocket;
}
//收到消息并显示
void ServerDialog::processTextMessage(QString message) {
	QString time = current_date_time->currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd");
	QString item = pSocket->peerAddress().toString();
	ui.receiveTextEdit->append(time + "" + item + "\n" + message);
}

//连接断开的操作
void ServerDialog::socketDisconnected() {
	ui.startButton->setEnabled(true);
	ui.stopButton->setEnabled(false);
	ui.sendButton->setEnabled(false);
	ui.sendTextedit->setEnabled(false);
	ui.receiveTextEdit->setEnabled(false);
	ui.cleanButton->setEnabled(false);
}

 

  • 4
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值