TCP协议通信

**特点:**优点不丢包,可以传输内容大的数据,
**缺点:**传输效率慢于UDP,
**使用场合:**适合进程间文件,图片,视频发送。
**原理:**3次握手,第一次客户端发送连接请求,服务端确认AK置1,第二次服务端返回确认连接请求,客户端接收AK置1,第三次客户端NAK置1,发送连接成功,服务端NAK置1,确认连接成功。

客户端:
初始化绑定IP和端口号
QTcpSocket tcpSocket = new QTcpSocket(this);
Int port = 5555;
tcpSocket.connectToHost(“127.0.0.1”,port);
发送数据,
QByteArray sendData;
tcpSocket.write(sendData,sendData.length);
接收数据

服务端:
初始化某些地址和端口号监听连接;
QTcpServer tcpServer = new QTcpServer(this);
Int port = 5555;
tcpServer.listen(QHostAddress::Any,port);
connect(tcpServer,&QTcpServer::newConnection;this,&Dialog::incomming);
连接成功建立通信;
QTcpSocket tcpSocket = tcpServer.nextPending();
QList> tcpSocketList;
tcpSocketList.append(tcpSocket);
connect(tcpSocket,&QAbstractSocket::connected,this,&Dialog::onConnected);
connect(tcpSocket,&QAbstractSocket::disconnected,this,&Dialog::onDisconnected);
void (QAbstractSocket *send)(QAbstractSocket::SocketError socketError) = &QAbstractSocket:error;
Void (Dialog *rev)(QAbstractSocket::SocketError socketError) = &Dialog::onError;
connect(tcpSocket,send,this,rev);
connect(tcpSocket,&QIODevice::readyRead,this,&Dialog::readData);
接收数据
QObject *obj = this.sender();
QTcpSocket *socket = qobject_cast(obj);
While(socket.bytesAvailiable())
{
Int size = socket.bytesAvailiable();
QByteArray revData;
revData.resize(size);
Socket.read(revData.data(),revData.size());
QString msg = QString::fromLocat8Bit(revData,revData,size());
}
发送数据

你可能感兴趣的:(tcp/ip,网络协议,网络)