Qt完成了第一个项目。
实现局域网下的简单通信。
功能:实现登录,注册,获得IP,实现UDP通信,服务端转发文件(暂未实现)
服务端代码
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTcpServer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
//建立监听套接字
QTcpServer *server=nullptr;
protected slots:
void dealclient();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
totcosocket.h
#ifndef TOTCOSOCKET_H
#define TOTCOSOCKET_H
#include <QWidget>
#include <QTcpSocket>
namespace Ui {
class totcosocket;
}
class totcosocket : public QWidget
{
Q_OBJECT
public:
explicit totcosocket(QTcpSocket *socket,QWidget *parent = 0);
~totcosocket();
QVector<QString> IP;
QVector<QString> PORT;
private:
Ui::totcosocket *ui;
};
#endif // TOTCOSOCKET_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "ui_mainwindow.h"
#include "totcosocket.h"
#include <QTcpSocket>
#include <QHostAddress>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//给监听套接字分配空间
this->server=new QTcpServer(this);
//设置端口和IP地址
server->listen(QHostAddress::Any,19999);
//等待客户端连接
connect(server,&QTcpServer::newConnection,this,&MainWindow::dealclient);
}
void MainWindow::dealclient()
{
//接收新的客户端
QTcpSocket *socket=server->nextPendingConnection();
//将分派到功能模块中,对该socket进行处理
totcosocket *tmpsocket=new totcosocket(socket);
this->hide();
tmpsocket->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
totcosocket.cpp
#include "totcosocket.h"
#include "ui_totcosocket.h"
#include <QSqlDatabase>
#include <QMessageBox>
#include <QHostAddress>
#include <QSqlQuery>
#include <QThread>
#include <QAbstractSocket>
totcosocket::totcosocket(QTcpSocket *socket,QWidget *parent) :
QWidget(parent),
ui(new Ui::totcosocket)
{
ui->setupUi(this);
//检查
//获取对方的IP和端口
QString ip=socket->peerAddress().toString();
ushort port=socket->peerPort();
QString port_s=QString::number(port);
QString temp=QString("{%1:%2}:连接成功").arg(ip).arg(port_s);
ui->textEdit->setText(temp);
IP.push_back(ip);
PORT.push_back(port_s);
connect(socket,&QTcpSocket::readyRead,[=](){
//读取发送过来的信息
QByteArray array=socket->readAll();
ui->textEdit->append(array);
//解析信息
QString str1=QString(array).section("##",0,0);
QString str2=QString(array).section("##",1,1);
QString str3=QString(array).section("##",2,2);
//连接数据库
QSqlDatabase db=QSqlDatabase::addDatabase("QS