最近因为项目原因。准备前后端进行分离。所有的接口全部通过websocket进行交互。
所以干脆先试写一个demo。
使用websocket进行通信。需要有服务端和客户端。(客户端和服务端是2个独立程序)

客户端

客户端只负责发消息和接受消息。
.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QProgressBar>
#include <QWebSocket>class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void Init();void Connect();protected slots:void onConnectClicked();  //点击连接按钮触发事件void onSendClicked();  //发送数据void onConnectServer(); //连接服务端void onDisConnectServer(); //断开连接void onReceiverData(const QString &msg); //接受数据。可以是json。使用qbytearray进行转化和解码private:QLineEdit *m_pAddressEdit=nullptr;QTextEdit *m_pTextEdit=nullptr;QPushButton *m_pConnectBtn=nullptr;QPushButton *m_pSendBtn=nullptr;QWebSocket *m_pReceiverSocket=nullptr;};
#endif // WIDGET_H

.cpp

#include "widget.h"
#include <QHBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent)
{this->resize(800,600);Init();Connect();}Widget::~Widget()
{}void Widget::Init()
{m_pAddressEdit=new QLineEdit(this);m_pTextEdit=new QTextEdit(this);m_pConnectBtn=new QPushButton(tr("Connect"),this);m_pSendBtn=new QPushButton(tr("Send"),this);m_pAddressEdit->setFixedSize(230,27);m_pConnectBtn->setFixedSize(150,27);m_pSendBtn->setFixedSize(150,27);QWidget *titleWgt=new QWidget(this);QHBoxLayout *titleLayout=new QHBoxLayout(this);titleLayout->addWidget(m_pAddressEdit);titleLayout->addWidget(m_pConnectBtn);titleLayout->addWidget(m_pSendBtn);titleLayout->setMargin(10);titleLayout->setSpacing(10);titleWgt->setLayout(titleLayout);QVBoxLayout *mainLayout=new QVBoxLayout(this);mainLayout->addWidget(titleWgt);mainLayout->addWidget(m_pTextEdit);mainLayout->setMargin(0);mainLayout->setSpacing(0);this->setLayout(mainLayout);m_pSendBtn->setEnabled(false);m_pReceiverSocket=new QWebSocket;m_pReceiverSocket->setParent(this);}void Widget::Connect()
{connect(m_pConnectBtn,&QPushButton::clicked,this,&Widget::onConnectClicked);connect(m_pSendBtn,&QPushButton::clicked,this,&Widget::onSendClicked);connect(m_pReceiverSocket,&QWebSocket::connected,this,&Widget::onConnectServer);connect(m_pReceiverSocket,&QWebSocket::disconnected,this,&Widget::onDisConnectServer);connect(m_pReceiverSocket,&QWebSocket::textMessageReceived,this,&Widget::onReceiverData);
}void Widget::onConnectClicked()
{QString strAddress=m_pAddressEdit->text();if(strAddress!=""){m_pReceiverSocket->open(QUrl(strAddress));  /* ws://localhost:2022 */ //localhost可变为ip地址,这里只是方便测试//冒号后面是端口号}
}
void Widget::onSendClicked()
{if(!m_pTextEdit->toPlainText().isEmpty())   {m_pReceiverSocket->sendTextMessage(m_pTextEdit->toPlainText());}}void Widget::onConnectServer()
{m_pConnectBtn->setEnabled(false);m_pSendBtn->setEnabled(true);m_pTextEdit->append(QString("Address:%1  Port:%2").arg(m_pReceiverSocket->localAddress().toString()).arg(m_pReceiverSocket->localPort()));
}void Widget::onDisConnectServer()
{m_pConnectBtn->setEnabled(true);m_pSendBtn->setEnabled(false);m_pTextEdit->append("DisConnet To Server");
}void Widget::onReceiverData(const QString &msg)
{m_pTextEdit->append(msg);
}

服务端

服务端需要有一个websocketserver进行监听端口,当有消息过来可进行处理。
.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QProgressBar>
#include <QWebSocket>
#include <QWebSocketServer>
#include <vector>class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void Init();void Connect();signals:void sendMessage(QString);protected slots:void onListenClicked();  //监听事件触发void onNewConnection();  //有新的连接加入private:void ClearClient();  //清除所有连接private:QLineEdit *m_pAddressEdit=nullptr;QLineEdit *m_pPortEdit=nullptr;QTextEdit *m_pTextEdit=nullptr;QPushButton *m_pConnectBtn=nullptr;QPushButton *m_pSendBtn=nullptr;QWebSocketServer *m_pServerSocket=nullptr;QVector<QWebSocket *>ClientList;};
#endif // WIDGET_H

.cpp

#include "widget.h"
#include <QHBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent)
{Init();Connect();
}Widget::~Widget()
{//这里是重点。一定要在析构函数中对server进行关闭。不然程序会奔溃ClearClient();m_pServerSocket->close();
}void Widget::Init()
{m_pAddressEdit=new QLineEdit(this);m_pPortEdit=new QLineEdit(this);m_pTextEdit=new QTextEdit(this);m_pConnectBtn=new QPushButton(tr("Listen"),this);m_pSendBtn=new QPushButton(tr("Send"),this);m_pAddressEdit->setFixedSize(230,27);m_pPortEdit->setFixedSize(100,27);m_pConnectBtn->setFixedSize(150,27);m_pSendBtn->setFixedSize(150,27);QWidget *titleWgt=new QWidget(this);QHBoxLayout *titleLayout=new QHBoxLayout(this);titleLayout->addWidget(m_pAddressEdit);titleLayout->addWidget(m_pPortEdit);titleLayout->addWidget(m_pConnectBtn);titleLayout->addWidget(m_pSendBtn);titleLayout->setMargin(10);titleLayout->setSpacing(10);titleWgt->setLayout(titleLayout);QVBoxLayout *mainLayout=new QVBoxLayout(this);mainLayout->addWidget(titleWgt);mainLayout->addWidget(m_pTextEdit);mainLayout->setMargin(0);mainLayout->setSpacing(0);this->setLayout(mainLayout);m_pSendBtn->setEnabled(false);//server Listenm_pServerSocket=new QWebSocketServer("Server",QWebSocketServer::NonSecureMode,this);m_pSendBtn->setEnabled(false);}void Widget::Connect()
{connect(m_pConnectBtn,&QPushButton::clicked,this,&Widget::onListenClicked);connect(m_pServerSocket,&QWebSocketServer::newConnection,this,&Widget::onNewConnection);connect(m_pSendBtn,&QPushButton::clicked,[this](){if(!m_pTextEdit->toPlainText().isEmpty())emit sendMessage(m_pTextEdit->toPlainText());});
}void Widget::onListenClicked()
{if(m_pConnectBtn->text()!="Listen"){m_pSendBtn->setEnabled(false);m_pConnectBtn->setText("Listen");m_pServerSocket->close();ClearClient();}else{QHostAddress address;if(m_pAddressEdit->text()=="Any")  //可进行监听任意地址{address=QHostAddress::Any;}else{address=QHostAddress(m_pAddressEdit->text());  //监听指定地址}if(m_pServerSocket->listen(address,m_pPortEdit->text().toUInt())){m_pSendBtn->setEnabled(true);  //成功监听。m_pConnectBtn->setText("Dislisten");}}
}void Widget::onNewConnection()
{//监听只能监听一个ip地址。不能同时监听多个QWebSocket *socket=m_pServerSocket->nextPendingConnection();if(!socket)return;m_pTextEdit->append(QString("[new Connect] Address:%1    prot:%2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));ClientList.push_back(socket);connect(socket,&QWebSocket::textMessageReceived,[this](const QString &msg){m_pTextEdit->append(msg);});connect(this,&Widget::sendMessage,socket,&QWebSocket::sendTextMessage);connect(socket,&QWebSocket::disconnected,[this,socket](){ClientList.removeAll(socket);socket->deleteLater();});
}void Widget::ClearClient()
{for(int i=0;i<ClientList.size();++i){ClientList[i]->disconnect();ClientList[i]->close();}ClientList.clear();}

效果图:

其实我偷了个懒。应该使用2个texteit进行接受和发送。我写在一个里面。自己修改下就可以进行使用。
觉得有用记得点个赞。
ヾ( ̄▽ ̄)ByeBye

QwebSocket即时通信相关推荐

  1. 飞信2015服务器未响应,即时通信天下已定 飞信再难复活

    谈及飞信,或许移动的老用户会有印象.移动旗下的飞信曾名噪一时,便捷的通讯工具而且可以与短信无缝对接,但随着智能手机的普及微信出现,飞信悄然失去了光彩.而如今移动虽然想重金砸活飞信,但飞信复活已经难于上 ...

  2. .NET 即时通信,WebSocket服务端实例

    即时通信常用手段 1.第三方平台 谷歌.腾讯 环信等多如牛毛,其中谷歌即时通信是免费的,但免费就是免费的并不好用.其他的一些第三方一般收费的,使用要则限流(1s/限制x条消息)要么则限制用户数. 但稳 ...

  3. 即时通信是机遇也是挑战

    2019独角兽企业重金招聘Python工程师标准>>> 即时通信给运营商带来哪些挑战? 即时通信将分流运营商的传统业务     即时通信软件不仅与运营商提供的短信.语音一样,可以实现 ...

  4. iOS开发之使用XMPPFramework实现即时通信(二)

    上篇的博客iOS开发之使用XMPPFramework实现即时通信(一)只是本篇的引子,本篇博客就给之前的微信加上即时通讯的功能,主要是对XMPPFramework的使用.本篇博客中用到了Spark做测 ...

  5. WebSocket 实现 Web 端即时通信

    点击上方 好好学java ,选择 星标 公众号 重磅资讯.干货,第一时间送达 今日推荐:牛人 20000 字的 Spring Cloud 总结,太硬核了~ 前言 WebSocket 是HTML5开始提 ...

  6. (转)基于即时通信和LBS技术的位置感知服务(一):提出问题及解决方案

    一.前言.提出问题 公司最近举行2011年度创新设计大赛,快年底了正打算写写2010年以来Android开发的心得与经验,正好同事出了个点子:假如A和B两个人分别在不同的地点,能不能实现这样的功能,让 ...

  7. C语言 linux环境基于socket的简易即时通信程序

    转载请注明出处:http://www.cnblogs.com/kevince/p/3891033.html      --By Kevince 最近在看linux网络编程相关,现学现卖,就写了一个简易 ...

  8. 使用flask_socketio实现客户端间即时通信

    关于flask_socketio的入门可以看我的上一篇博客<使用flask_socketio实现服务端向客户端定时推送> 用socketio实现即时通信十分简单,只需要客户端发送用户输入的 ...

  9. 中油即时通信电脑版_市场营销之即时通讯营销

    ✎ IM营销又叫即时通讯营销(instantmessaging),是企业通过即时工具im推广产品和品牌,以实现目标客户挖掘和转化的网络营销方式. 封面设计丨Sweety 责编丨花花 第60篇丨每日一篇 ...

  10. 基于Android的聊天软件,Socket即时通信,实现用户在线聊天

    基于Android的聊天软件,Socket即时通信,单聊,聊天室,可自行扩展功能,完善细节. [实例功能] 1.运行程序,登录界面, 注册账号功能 2.进入主界面,有通讯录, 个人信息. 3.点击好友 ...

最新文章

  1. tf.nn.embedding_lookup()的用法
  2. [JS] for-each和map()的区别
  3. atom 中首次使用git_使用Atom获得更好的Git提交消息
  4. python积分管理系统_python实现每天自动签到领积分的示例代码
  5. 2021-07-27 对labelme标注出来的JSON文件进行灰度图转化(标签值0.1.2.3.4)
  6. 比特币现金成为第二个最有价值的区块链
  7. 微服务下的容器部署和管理平台Rancher
  8. 使用预训练的卷积神经网络(猫狗图片分类)
  9. 谷歌机器学习规则:机器学习工程的43条最佳实践经验
  10. stein法求gcd 学习笔记
  11. Linux函数--inet_pton / inet_ntop
  12. win10一直卡在自动修复_分享:win10自动修复过程中无法正确启动怎么办?
  13. 图像分割中dc_loss忽视标签实现
  14. 疫情之下 SaaS 市场两极分化,SaaS 厂商如何突围严峻形势?
  15. 毕设系列之 -- 基于大数据的全国热门旅游景点数据分析与可视化
  16. Ubuntu18/Linux 安装 Halcon21.05
  17. powerdesign165破解以及使用教程
  18. 小米路由修改服务器密码,小米路由器怎么重新设置密码?
  19. Android Property
  20. 熔断机制什么意思_熔断机制是什么意思 股市熔断是什么意思

热门文章

  1. 微信小程序学习笔记-(9)-仿智行火车票
  2. 网络基础知识(黑马教程笔记)-5-路由
  3. el-option传两个值_如意芳霏三对CP三种甜,傅容与徐晋夫唱妇随,甜蜜值爆棚
  4. python正则匹配_Python中的正则表达式(re)
  5. a4b5笔记本大小对比_2L大小的迷你电脑上班拎着走
  6. php 构造函数参数传值,php 构造函数参数
  7. python读取csv内容变为nan,python – 获取pandas.read_csv以空字符串而不是nan读取空值...
  8. (1)快速了解Redis
  9. id和instancetype
  10. 字符串的迷之算法——KMP,AC自动机,后缀数组