这是QT TcpSocket 服务端,流程是,被连接上之后,接收到客户端发来的数据,进行处理,在返回给相应客户端相应的数据。下面是部分代码:
QT TcpSocket 服务端
QTcpServer * server;
QTcpSocket * clientConnection;
server = new QTcpServer();
/*
* 设置监听端口,这里12345是端口号
* 绑定信号槽
* newConnection():表示当tcp有新连接时就发送信号
*/
server->listen(QHostAddress::Any, 12345);
connect(server, SIGNAL(newConnection()), this, SLOT(slot_acceptConnection()));
/*
* 槽函数,当有新的tcp连接的时候,就执行该槽函数
* nextPendingConnection():我们获取已经建立的连接的子套接字,就是刚连接上的这个客户端
* 绑定信号槽
*/
void VgTcpSocket::slot_acceptConnection()
{
clientConnection = server->nextPendingConnection();
connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slot_readClient()));
}
/*
* 槽函数,当tcp新的连接发送数据给服务端时候就执行该槽函数
* readAll():读数据
* write():回发数据给那个与他通信的连接
* 这里:在接收到数据之后,我们可以执行自己的逻辑运算,之后返回信息。
* 具体发送接受数据参考QT TcpSocket客户端。
*/
void VgTcpSocket::slot_readClient()
{
QString str = clientConnection->readAll();
char* data;
qint64 n_bit = clientConnection->write(data);
}
头文件:#include <QTcpSocket>
相关文章: