如果有人不知道qt在树莓派上如何安装,请看我上一个连接:https://blog.csdn.net/qq_43433255/article/details/84678512
首先明确:聊天程序分为客户端与服务端,服务端。分别实现不同的功能。
服务端:
创建项目,确定名字与路径。
备注:在后面的main.cpp要导入相关的.h文件,如果不是很清楚的,请按照我的命名一直走下去,避免无故采坑。
确定一个classname:
在项目chat_test右键、分别新建tcpclientsocket.h和tcpclientsocket.cpp;
然后是dialog.h和dialog.cpp,最后效果是:
到此,我们就应该写代码了(这才是最重要的部分):
chat_test.pro的代码:
添加如下代码:
QT += networt
dialog.h的代码:
#ifndef TCPSERVER_H
#defineTCPSERVER_H
#include<QDialog>
#include<QListWidget>
#include<QLabel>
#include<QLineEdit>
#include<QPushButton>
#include<QGridLayout>
#include"tcpserver.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
tcpclientsocket.h的代码:
#ifndef TCPCLIENTSOCKET_H
#define TCPCLIENTSOCKET_H
#include <QTcpSocket>
#include <QObject>
//用于与客户端通信
class TcpClientSocket : public QTcpSocket
{
Q_OBJECT
public:
TcpClientSocket(QObject *parent=0);
signals:
void updateClients(QString,int);
void disconnected(int);
protected slots:
void dataReceived();
voidslotDisconnected();
};
#endif // TCPCLIENTSOCKET_H
tcpserver.h的代码:
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
#include <QObject>
#include "tcpclientsocket.h"
//TCP服务器,监听指定端口的TCP连接
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
dialog.cpp的代码:
#include "dialog.h"
TcpServer::TcpServer(QWidget *parent,Qt::WindowFlags f):QDialog(parent,f)
{
setWindowTitle(tr("TCP Server"));
ContentListWidget = new QListWidget;
PortLabel = new QLabel(tr("端口:"));
PortLineEdit =new QLineEdit;
CreateBtn = newQPushButton(tr("创建聊天室"));
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=1234;
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));
}
tcpclientsocket.cpp的代码:
#include "tcpclientsocket.h"
TcpClientSocket::TcpClientSocket(QObject *parent)
{
connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));
connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
}
void TcpClientSocket::dataReceived()
{
while(bytesAvailable()>0)
{
int length= bytesAvailable();
charbuf[1024];
read(buf,length);
QStringmsg=buf;
emitupdateClients(msg, length);
}
}
void TcpClientSocket::slotDisconnected()
{
emit disconnected(this->socketDescriptor());
}
tcpserver.cpp的代码:
#include "tcpserver.h"
Server::Server(QObject *parent,int port)
:QTcpServer(parent)
{
listen(QHostAddress::Any,port);
}
//出现一个新的连接时触发
void Server::incomingConnection(int socketDescriptor)
{
TcpClientSocket *tcpClientSocket = new TcpClientSocket(this);
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;
}
}
}
//将断开连接的TcpSocket对象删除
void Server::slotDisconnected(int descriptor)
{
for(inti=0;i<tcpClientSocketList.count();i++)
{
QTcpSocket *item = tcpClientSocketList.at(i);
if(item->socketDescriptor()==descriptor)
{
tcpClientSocketList.removeAt(i);
return;
}
}
return;
}
Main.cpp的代码:
#include "tcpclientsocket.h"
#include "tcpserver.h"
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TcpServer w;
w.show();
return a.exec();
}
运行调试,结果:
客户端:
命名为TcpClient:
classname为:tcpclient
TcpClient.pro代码:
QT += network
tcpClient.h的代码:
#ifndefTCPCLIENT_H
#defineTCPCLIENT_H
#include<QDialog>
#include<QListWidget>
#include<QLineEdit>
#include<QPushButton>
#include<QLabel>
#include<QGridLayout>
#include<QHostAddress>
#include<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
tcpclient.cpp的代码:
#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("发送"));
userNameLabel = new QLabel(tr("用户名:"));
userNameLineEdit = new QLineEdit;
serverIPLabel = new QLabel(tr("服务器地址:"));
serverIPLineEdit = new QLineEdit;
portLabel = new QLabel(tr("端口:"));
portLineEdit = new QLineEdit;
enterBtn= new QPushButton(tr("进入聊天室"));
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 = 1234;
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("进入聊天室"));
}
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()));
}
}
main.cpp的代码:
#include "tcpclient.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TcpClient w;
w.show();
return a.exec();
}
运行效果:
最后在同一个局域网,进行聊天的最终效果:
另外一个树莓派:
另外,附上连接:https://blog.csdn.net/cungudafa/article/details/84501611