#include "server.h"
#include "ui_server.h"
Server::Server(QWidget *parent) :
QWidget(parent),
ui(new Ui::Server)
{
port = 666;
socket = new QUdpSocket(this); 在.h文件中包含了QUdpSocket类,在工程中增加了network,socket是在.h文件中定义的指针;
//根据系统的不同,导致绑定的模式时不同的,通过条件编译选择模式;
#ifdef Q_OS_LINUX
socket->bind(port, QUdpSocket::ShareAddress);
#else //Q_OS_WIN32
socket->bind(port, QUdpSocket::ReuseAddressHint);
#endif
connect(socket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
ui->setupUi(this);
}
Server::~Server()
{
delete ui;
}
void Server::readPendingDatagrams() //开始读数据;
{
while(socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize()); //通过socket获取数据包的长度;
socket->readDatagram(datagram.data(),datagram.size());
decodeMessage(datagram); //解析消息;
}
}
void Server::decodeMessage(const QByteArray &ba)
{
QDataStream stream(ba);
QString nick, message;
stream >> nick >> message; //先读出第一个字符串,赋给nick(就是名字),第二个赋给消息内容;
showMessage(nick, message);
}
//用于打包消息;
QByteArray Server::encodeMessage(const QString &nick, const QString &message) const
{
QByteArray ba;
QDataStream stream(&ba, QIODevice::WriteOnly);
stream << nick << message;
return ba;
}
void Server::sendMessage()
{
QByteArray ba = encodeMessage(ui->ui_username->text(), //获取使用者名字;
ui->textEdit->toPlainText()); //获取消息;
socket->writeDatagram(ba, QHostAddress::Broadcast, port);//初始化数据报;
}
void Server::showMessage(const QString &nick, const QString &message)
{
QString line = tr("<b>%1</b> says: <i>%2</i>").arg(nick).arg(message);
ui->textBrowser->append(line);
ui->textEdit->clear();
}
void Server::on_pushButton_clicked()
{
sendMessage();
}
这里仅仅是.cpp文件,是核心的逻辑部分,至于其他部分,希望读者自己完成;
上文用到类名是Server,其实两台机器之间通信,是不用服务器的,只要在一个网段内就可以;
转载于:https://blog.51cto.com/10901086/1876940