我覺得這部分代碼,你發佈的是客戶端,你應該像常見的手抖動服務器提供來自客戶端的請求。
在服務器端,您以特定格式提供日期/時間,客戶端可以識別併發送它。看起來更像是客戶/服務器編程檢查Local Fortune Client和Local Fortune Server的例子。
這裏是你的客戶端簡單的例子:
void Client::startTransfer()
{
client.write("Hi server send time");
client.flush();
client.waitForBytesWritten(300);
}
和你的服務器端例如:
上newconnection
插槽服務器的客戶端數據連接到客戶端一樣消息的插槽。
void ServerSocket::newConnection()
{
QTcpSocket *clientsocket = mserver->nextPendingConnection();
connect(clientsocket , SIGNAL(readyRead()) , this , SLOT(clientMessage()));
}
,並在插槽客戶端消息響應它
void ServerSocket::clientMessage()
{
QTcpSocket* client = (QTcpSocket*)sender();
QString message(client->readAll());
if (message == "Hi server send time")
{
client->write(QDateTime::currentDateTimeUtc().toString().toLatin1());
client->flush();
client->waitForBytesWritten(300);
}
}
這裏是需要完整的代碼:
servesocket.h
#ifndef SERVERSOCKET_H
#define SERVERSOCKET_H
#include <QObject>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
class ServerSocket : public QObject
{
Q_OBJECT
public:
explicit ServerSocket(QObject *parent = nullptr);
QTcpServer *mserver;
signals:
public slots:
void newConnection();
void clientMessage();
};
#endif // SERVERSOCKET_H
serversocket.cpp
#include "serversocket.h"
#include <QDateTime>
ServerSocket::ServerSocket(QObject *parent) : QObject(parent)
{
mserver = new QTcpServer(this);
mserver->connect(mserver , SIGNAL(newConnection()) , this , SLOT(newConnection()));
if(!mserver->listen(QHostAddress::Any , 1234))
{
qDebug() << "Server initilize failed";
}
}
void ServerSocket::newConnection()
{
QTcpSocket *clientsocket = mserver->nextPendingConnection();
connect(clientsocket , SIGNAL(readyRead()) , this , SLOT(clientMessage()));
}
void ServerSocket::clientMessage()
{
QTcpSocket* client = (QTcpSocket*)sender();
QString message(client->readAll());
if (message == "Hi server send time")
{
client->write(QDateTime::currentDateTimeUtc().toString().toLatin1());
client->flush();
client->waitForBytesWritten(300);
}
}
主窗口標題
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QLineEdit>
#include <QMainWindow>
#include <QSerialPort>
#include "serversocket.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);//:QMainWindow(parent)
~MainWindow();
private slots:
private:
Ui::MainWindow *ui;
ServerSocket * server;
};
#endif // MAINWINDOW_H
主窗口CPP
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
server = new ServerSocket();
}
MainWindow::~MainWindow()
{
delete ui;
}
你MEA n本地*系統日期和時間?還是那個* remote *系統? –
客戶端無法獲得服務器時間,您必須將其與您的數據包一起發送。'QDateTime dateTime = dateTime.currentDateTime();'和 'QString dateTimeString = dateTime.toString(「yyyy-MM-dd_hh-mm-ss」);' – aghilpro
@aghilpro你能告訴我how.detail代碼。我用你的代碼替換消息,它只是發送到服務器。 – explorer104