全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

QT网络编程Tcp下C/S架构的即时通信实例

先写一个客户端,实现简单的,能加入聊天,以及加入服务器的界面。

#ifndef TCPCLIENT_H
#define TCPCLIENT_H
 
#include <QDialog>
#include <QListWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include <QtNetWork/QHostAddress>
#include <QtNetWork/QTcpSocket>
 
class TcpClient : public QDialog
{
 Q_OBJECT
 
public:
 TcpClient(QWidget *parent = 0,Qt::WindowFlags f=0);
 ~TcpClient();
private:
 QListWidget *contentListWidget;
 QLineEdit *sendLineEdit;
 QPushButton *sendBtn;
 QLabel *userNameLabel;
 QLineEdit *userNameLineEdit;
 QLabel *serverIPLabel;
 QLineEdit *serverIPLineEdit;
 QLabel *portLabel;
 QLineEdit *portLineEdit;
 QPushButton *enterBtn;
 QGridLayout *mainLayout;
 bool status;
 int port;
 QHostAddress *serverIP;
 QString userName;
 QTcpSocket *tcpSocket;
public slots:
 void slotEnter();
 void slotConnected();
 void slotDisconnected();
 void dataReceived();
 void slotSend();
};
 
#endif // TCPCLIENT_H

有一个加入服务器的按钮,还有一个发送消息的按钮,在头文件,先定义两个函数。

#include "tcpclient.h"
#include <QMessageBox>
#include <QHostInfo>
 
TcpClient::TcpClient(QWidget *parent,Qt::WindowFlags f)
 : QDialog(parent,f)
{
 setWindowTitle(tr("TCP Client"));
 
 contentListWidget = new QListWidget;
 
 sendLineEdit = new QLineEdit;
 sendBtn = new QPushButton(tr("send"));
 
 userNameLabel = new QLabel(tr("name"));
 userNameLineEdit = new QLineEdit;
 
 serverIPLabel = new QLabel(tr("server"));
 serverIPLineEdit = new QLineEdit;
 
 portLabel = new QLabel(tr("port"));
 portLineEdit = new QLineEdit;
 
 enterBtn= new QPushButton(tr("join chat"));
 
 mainLayout = new QGridLayout(this);
 mainLayout->addWidget(contentListWidget,0,0,1,2);
 mainLayout->addWidget(sendLineEdit,1,0);
 mainLayout->addWidget(sendBtn,1,1);
 mainLayout->addWidget(userNameLabel,2,0);
 mainLayout->addWidget(userNameLineEdit,2,1);
 mainLayout->addWidget(serverIPLabel,3,0);
 mainLayout->addWidget(serverIPLineEdit,3,1);
 mainLayout->addWidget(portLabel,4,0);
 mainLayout->addWidget(portLineEdit,4,1);
 mainLayout->addWidget(enterBtn,5,0,1,2);
 
 status = false;
 
 port = 8010;
 portLineEdit->setText(QString::number(port));
 
 serverIP =new QHostAddress();
 
 connect(enterBtn,SIGNAL(clicked()),this,SLOT(slotEnter()));
 connect(sendBtn,SIGNAL(clicked()),this,SLOT(slotSend()));
 
 sendBtn->setEnabled(false);
}
 
TcpClient::~TcpClient()
{
 
}
 
void TcpClient::slotEnter()
{
 if(!status)
 {
  QString ip = serverIPLineEdit->text();
  if(!serverIP->setAddress(ip))
  {
   QMessageBox::information(this,tr("error"),tr("server ip address error!"));
   return;
  }
 
  if(userNameLineEdit->text()=="")
  {
   QMessageBox::information(this,tr("error"),tr("User name error!"));
   return;
  }
 
  userName=userNameLineEdit->text();
 
  tcpSocket = new QTcpSocket(this);
  connect(tcpSocket,SIGNAL(connected()),this,SLOT(slotConnected()));
  connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
  connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));
 
  tcpSocket->connectToHost(*serverIP,port);
 
  status=true;
 }
 else
 {
  int length=0;
  QString msg=userName+tr(":Leave Chat Room");
  if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg. length())
  {
   return;
  }
 
  tcpSocket->disconnectFromHost();
 
  status=false;
 }
}
 
void TcpClient::slotConnected()
{
 sendBtn->setEnabled(true);
 enterBtn->setText(tr("离开"));
 
 int length=0;
 QString msg=userName+tr(":Enter Chat Room");
 if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg.length())
 {
  return;
 }
}
 
void TcpClient::slotSend()
{
 if(sendLineEdit->text()=="")
 {
  return ;
 }
 
 QString msg=userName+":"+sendLineEdit->text();
 
 tcpSocket->write(msg.toLatin1(),msg.length());
 sendLineEdit->clear();
}
 
void TcpClient::slotDisconnected()
{
 sendBtn->setEnabled(false);
 enterBtn->setText(tr("join chat"));
}
 
void TcpClient::dataReceived()
{
 while(tcpSocket->bytesAvailable()>0)
 {
  QByteArray datagram;
  datagram.resize(tcpSocket->bytesAvailable());
 
  tcpSocket->read(datagram.data(),datagram.size());
 
  QString msg=datagram.data();
  contentListWidget->addItem(msg.left(datagram.size()));
 }
}

实现界面布局。在Enter槽函数中,确定加入还是离开的服务器的功能。如果加入了,就将消息,写到tcpsocket中,构造消。

服务端的头文件:

#ifndef TCPSERVER_H
#define TCPSERVER_H
 
#include <QDialog>
#include <QListWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include "server.h"
 
class TcpServer : public QDialog
{
 Q_OBJECT
 
public:
 TcpServer(QWidget *parent = 0,Qt::WindowFlags f=0);
 ~TcpServer();
private:
 QListWidget *ContentListWidget;
 QLabel *PortLabel;
 QLineEdit *PortLineEdit;
 QPushButton *CreateBtn;
 QGridLayout *mainLayout;
 int port;
 Server *server;
public slots:
 void slotCreateServer();
 void updateServer(QString,int);
};
 
#endif // TCPSERVER_H

这是服务端的界面的,把消息显示而已。实现这个布局。

#include "tcpserver.h"
 
TcpServer::TcpServer(QWidget *parent,Qt::WindowFlags f)
 : QDialog(parent,f)
{
 setWindowTitle(tr("TCP Server"));
 
 ContentListWidget = new QListWidget;
 
 PortLabel = new QLabel(tr(" port"));
 PortLineEdit = new QLineEdit;
 
 CreateBtn = new QPushButton(tr("create chat"));
 mainLayout = new QGridLayout(this);
 mainLayout->addWidget(ContentListWidget,0,0,1,2);
 mainLayout->addWidget(PortLabel,1,0);
 mainLayout->addWidget(PortLineEdit,1,1);
 mainLayout->addWidget(CreateBtn,2,0,1,2);
 
 port=8010;
 PortLineEdit->setText(QString::number(port));
 
 connect(CreateBtn,SIGNAL(clicked()),this,SLOT(slotCreateServer()));
}
 
TcpServer::~TcpServer()
{
 
}
 
void TcpServer::slotCreateServer()
{
 server = new Server(this,port);
 connect(server,SIGNAL(updateServer(QString,int)),this,SLOT(updateServer(QString,int)));
 
 CreateBtn->setEnabled(false);
}
 
void TcpServer::updateServer(QString msg,int length)
{
 ContentListWidget->addItem(msg.left(length));
}

创建TCP的套接字,以便实现服务端和客户端的通信。

#ifndef TCPCLIENTSOCKET_H
#define TCPCLIENTSOCKET_H
 
#include <QtNetWork/QTcpSocket>
#include <QObject>
 
class TcpClientSocket : public QTcpSocket
{
 Q_OBJECT
public:
 TcpClientSocket();
signals:
 void updateClients(QString,int);
 void disconnected(int);
protected slots:
 void dataReceived();
 void slotDisconnected();
};
 
#endif // TCPCLIENTSOCKET_H

以上是头文件,具体的是:

#include "tcpclientsocket.h"
 
TcpClientSocket::TcpClientSocket()
{
 connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));
 connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
}
 
void TcpClientSocket::dataReceived()
{
 while(bytesAvailable()>0)
 {
  int length = bytesAvailable();
  char buf[1024];
  read(buf,length);
 
  QString msg=buf;
  emit updateClients(msg,length);
 }
}
 
void TcpClientSocket::slotDisconnected()
{
 emit disconnected(this->socketDescriptor());
}

实现服务器,头文件:

#ifndef SERVER_H
#define SERVER_H
 
#include <QtNetWork/QTcpServer>
#include <QObject>
#include "tcpclientsocket.h"
 
class Server : public QTcpServer
{
 Q_OBJECT
public:
 Server(QObject *parent=0,int port=0);
 QList<TcpClientSocket*> tcpClientSocketList;
signals:
 void updateServer(QString,int);
public slots:
 void updateClients(QString,int);
 void slotDisconnected(int);
protected:
 void incomingConnection(int socketDescriptor);
};
 
#endif // SERVER_H
#include "server.h"
 
Server::Server(QObject *parent,int port)
 :QTcpServer(parent)
{
 listen(QHostAddress::Any,port);
}
 
void Server::incomingConnection(int socketDescriptor)
{
 TcpClientSocket *tcpClientSocket = new TcpClientSocket;
 connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
 connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));
 
 tcpClientSocket->setSocketDescriptor(socketDescriptor);
 
 tcpClientSocketList.append(tcpClientSocket);
}
 
void Server::updateClients(QString msg,int length)
{
 emit updateServer(msg,length);
 for(int i=0;i<tcpClientSocketList.count();i++)
 {
  QTcpSocket *item = tcpClientSocketList.at(i);
  if(item->write(msg.toLatin1(),length)!=length)
  {
   continue;
  }
 }
}
 
void Server::slotDisconnected(int descriptor)
{
 for(int i=0;i<tcpClientSocketList.count();i++)
 {
  QTcpSocket *item = tcpClientSocketList.at(i);
  if(item->socketDescriptor()==descriptor)
  {
   tcpClientSocketList.removeAt(i);
   return;
  }
 }
 return;
}

实现后的界面:

以上这篇QT网络编程Tcp下C/S架构的即时通信实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


# 即时通信架构  # Qt中TCP协议通信详解  # QT实现简单TCP通信  # Qt实现简单的TCP通信  # QT编写tcp通信工具(Client篇)  # QT网络通信TCP客户端实现详解  # Qt TCP网络通信学习  # Qt网络编程实现TCP通信  # QT5实现简单的TCP通信的实现  # 基于QT的TCP通信服务的实现  # Qt TCP实现简单通信功能  # 头文件  # 服务端  # 给大家  # 的是  # 客户端  # 这是  # 希望能  # 还有一个  # 写到  # 就将  # 这篇  # 小编  # 大家多多  # 有一个  # 网络编程  # 即时通信  # 发送消息  # 先写  # slotEnter  # slotConnected 


相关文章: 怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?  Swift中swift中的switch 语句  如何快速搭建安全的FTP站点?  c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】  如何通过远程VPS快速搭建个人网站?  如何高效生成建站之星成品网站源码?  ,柠檬视频怎样兑换vip?  七夕网站制作视频,七夕大促活动怎么报名?  如何实现建站之星域名转发设置?  交易网站制作流程,我想开通一个网站,注册一个交易网址,需要那些手续?  如何快速打造个性化非模板自助建站?  保定网站制作方案定制,保定招聘的渠道有哪些?找工作的人一般都去哪里看招聘信息?  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  代购小票制作网站有哪些,购物小票的简要说明?  手机怎么制作网站教程步骤,手机怎么做自己的网页链接?  如何注册花生壳免费域名并搭建个人网站?  如何快速登录WAP自助建站平台?  建站之星代理如何优化在线客服效率?  建站之星代理如何获取技术支持?  开心动漫网站制作软件下载,十分开心动画为何停播?  c# F# 的 MailboxProcessor 和 C# 的 Actor 模型  网站制作说明怎么写,简述网页设计的流程并说明原因?  javascript中对象的定义、使用以及对象和原型链操作小结  建站之星代理费用多少?最新价格详情介绍  JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)  建站之星会员如何解锁更多建站功能?  网站制作话术技巧,网站推广做的好怎么话术?  如何用花生壳三步快速搭建专属网站?  建站主机核心功能解析:服务器选择与网站搭建流程指南  江苏网站制作公司有哪些,江苏书法考级官方网站?  代刷网站制作软件,别人代刷火车票靠谱吗?  动图在线制作网站有哪些,滑动动图图集怎么做?  如何用西部建站助手快速创建专业网站?  如何通过cPanel快速搭建网站?  建站上传速度慢?如何优化加速网站加载效率?  SAX解析器是什么,它与DOM在处理大型XML文件时有何不同?  宝塔建站无法访问?如何排查配置与端口问题?  Bpmn 2.0的XML文件怎么画流程图  极客网站有哪些,DoNews、36氪、爱范儿、虎嗅、雷锋网、极客公园这些互联网媒体网站有什么差异?  ,网站推广常用方法?  c# await 一个已经完成的Task会发生什么  MySQL查询结果复制到新表的方法(更新、插入)  个人摄影网站制作流程,摄影爱好者都去什么网站?  湖南网站制作公司,湖南上善若水科技有限公司做什么的?  企业网站制作费用多少,企业网站空间一般需要多大,费用是多少?  唐山网站制作公司有哪些,唐山找工作哪个网站最靠谱?  建站之星收费标准详解:套餐费用及年费价格表一览  简单实现Android验证码  javascript中的try catch异常捕获机制用法分析  php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。