TCP通信
TCP的话要复杂点,必须先建立连接才能传输数据,分为server端和client端。
2.1.TCP client端
- #include <QtNetwork>
- QTcpSocket *client;
- char *data="hello qt!";
- client = new QTcpSocket(this);
- client->connectToHost(QHostAddress("10.21.11.66"), 6665);
- client->write(data);
TCP server端
- #include <QtNetwork>
- QTcpServer *server;
- QTcpSocket *clientConnection;
- server = new QTcpServer();
- server->listen(QHostAddress::Any, 6665);
- connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
- void acceptConnection()
- {
- clientConnection = server->nextPendingConnection();
- connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
- }
- void readClient()
- {
- QString str = clientConnection->readAll();
- //或者
- char buf[1024];
- clientConnection->read(buf,1024);
- }