code-prettify

2015年7月14日 星期二

Qt TcpSocket

Server 的部份使用 QTcpServer

呼叫 listen 函式開始接受 Client 連線,參數為 QHostAddress::Any, 8811

在 newConnection signal 接受 socket

QTcpSocket* socket = server->nextPendingConnection();

在 readyRead() signal 接收資料

QBtyeArray data = socket->readyAll()

使用 write() 傳送資料

簡單的範例:

  m_server = new QTcpServer();
connect(m_server, &QTcpServer::newConnection, [=]() { qDebug() << "new client socket"; QTcpSocket* socket = this->m_server->nextPendingConnection(); connect(socket, &QTcpSocket::disconnected, [=]() { qDebug() << "client socket disconnected"; socket->deleteLater(); }); connect(socket, &QTcpSocket::readyRead, [=]() { qDebug() << "client readyRead"; QString string = socket->readAll(); qDebug() << "Read: " << string; string = string.toUpper(); qDebug() << "Send " << string; socket->write(string.toLatin1()); socket->close(); }); }); m_server->listen(QHostAddress::Any, 8811); qDebug() << "server listen";


Client 直接使用 QTcpSocket

呼叮 connectToHost 與 server 連線
連上了會觸發 connected 訊號,斷線則是 disconnected
接收資料一樣是 readyRead

簡單的範例:

m_client = new QTcpSocket();

connect(m_client, &QTcpSocket::connected, [=]() {
qDebug() << "socket connected";

QString string = "Hi";
m_client->write(string.toLatin1());
qDebug() << "Send: " << string;
});

connect(m_client, &QTcpSocket::disconnected, [=]() {
qDebug() << "socket disconnected";
});

connect(m_client, &QTcpSocket::readyRead, [=]() {
qDebug() << "client readyRead";

QString string = m_client->readAll();
qDebug() << "Read: " << string;

m_client->close();
});

m_client->connectToHost("127.0.0.1", 8811);


資料來源:
Network Programming with Qt
http://doc.qt.io/qt-5/qtnetwork-programming.html

Sockets - Server & Client using QT
http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php

QTcpSocket Class
http://doc.qt.io/qt-5/qtcpsocket.html

沒有留言:

張貼留言