Qt TCP的客户端与服务端的连接

Qt TCP的客户端与服务端的连接

可以实现局域网内简单的信息传递(文件传输,稍后更新)

界面是用ui设计师做的简单设计

在这里插入图片描述

  1. 客户端

    (1)ClientWidget.h 头文件

    #ifndef CLIENTWIDGET_H
    #define CLIENTWIDGET_H
    
    #include <QWidget>
    #include "ui_ClientWidget.h"
    #include <QTcpSocket>
    #include <QHostAddress>
    #include <QTextCodec>
    
    class ClientWidget : public QWidget, public Ui::ClientWidget
    {
    	Q_OBJECT
    
    public:
    	ClientWidget(QWidget *parent = 0);
    	~ClientWidget();
    
    private slots:
    	//连接按钮
    	void onConnectButtonClicked();
    	//
    	void onTextEditRead();
    	//发送按钮
    	void onButtonSendClicked();
    
    	//获取对方发送的内容
    	void onRecesiveDataFromServer();
    
    	//断开连接
    	void onDisConnect();
    private:
    	//Ui::ClientWidget ui;
    	QTcpSocket *tcpSocket;
    };
    
    #endif // CLIENTWIDGET_H
    
    

    (2)ClientWidget.cpp文件

    #include "stdafx.h"
    #include "ClientWidget.h"
    #include <QPushButton>
    
    
    ClientWidget::ClientWidget(QWidget *parent)
    	: QWidget(parent)
    {
    	setupUi(this);
    	setWindowTitle(QString::fromWCharArray(L"客户端"));
    
    	tcpSocket = NULL;
    
    	//分配空间,指定父对象
    	tcpSocket = new QTcpSocket(this);
    
    	ButtonDisconnect->setEnabled(false);
    	//tcpSocket->abort();
    
    	//发送与服务器连接信号
    	connect(connectBtn, SIGNAL(clicked()), this, SLOT(onConnectButtonClicked()));
    	
    	//连接成功后接收到connected信号
    	connect(tcpSocket, SIGNAL(connected()), this, SLOT(onTextEditRead()));
    	//给服务器发送内容
    	connect(ButtonSend, SIGNAL(clicked()), this, SLOT(onButtonSendClicked()));
    	//接收来自服务器的内容,信号readReady
    	connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(onRecesiveDataFromServer()));
    
    	connect(ButtonDisconnect, SIGNAL(clicked()), this, SLOT(onDisConnect()));
    	
    }
    
    ClientWidget::~ClientWidget()
    {
    
    }
    
    void ClientWidget::onConnectButtonClicked()
    {
    	//获取服务器IP和端口
    	QString ipStr = LineEditIPName->text();
    	qint16 portName = LineEditPortName->text().toInt();
    	QHostAddress ip = QHostAddress(ipStr);
    	//主动和服务器建立连接
    	tcpSocket->connectToHost(ip, portName);
    }
    
    void ClientWidget::onTextEditRead()
    {
    	TextEditRead->setText(QString::fromLocal8Bit("成功和服务器建立好连接!!!"));
    
    	connectBtn->setEnabled(false);
    	ButtonDisconnect->setEnabled(true);
    
    }
    
    void ClientWidget::onButtonSendClicked()
    {
    	if (tcpSocket == NULL)
    	{
    		return;
    	}
    	//获取编辑框内容
    	QString str = TextEditWrite->toPlainText();
    
    	//发送文本内容
    	tcpSocket->write(str.toUtf8().data());
    
    	TextEditWrite->clear();
    }
    
    void ClientWidget::onRecesiveDataFromServer()
    {
    	QByteArray arrayAll = tcpSocket->readAll();
    
    	QTextCodec *tc = QTextCodec::codecForName("UTF-8");
    	QString str = tc->toUnicode(arrayAll);
    
    	//追加到读取编辑区中
    	TextEditRead->append(str);
    }
    
    void ClientWidget::onDisConnect()
    {
    	if (tcpSocket == NULL)
    	{
    		return;
    	}
    
    	tcpSocket->disconnectFromHost();
    
    	tcpSocket->close();
    	connectBtn->setEnabled(true);
    
    	ButtonDisconnect->setEnabled(false);
    	
    	TextEditRead->setText(QString::fromLocal8Bit("连接已断开!!!"));
    }
    
    
  2. 服务器

(1)ServerWidget.h文件

#ifndef SERVERWIDGET_H
#define SERVERWIDGET_H

#include <QtGui/QWidget>
#include "ui_ServerWidget.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
#include <QTextCodec>
class ServerWidget : public QWidget
{
	Q_OBJECT	

public:
	ServerWidget(QWidget *parent = 0, Qt::WFlags flags = 0);
	~ServerWidget();
	QTcpServer *tcpServer;
	QTcpSocket *tcpSocket;

private slots:
	void OnConnectTcpServer(); 

	void OnSendButtonClicked();

	void OnCloseButtonClicked();

	void OnSeResiveData();

	void OnDisconnected();

private:
	Ui::ServerWidgetClass ui;
};

#endif // SERVERWIDGET_H

(2)ServerWidget.cpp 文件

#include "stdafx.h"
#include "ServerWidget.h"

ServerWidget::ServerWidget(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags)
{
	ui.setupUi(this);
	tcpServer = NULL;
	tcpSocket = NULL;
	setWindowTitle(QString::fromWCharArray(L"服务器(端口:8888)"));
	//箭筒套接字,指定父对象,让其自动回收空间
	tcpServer = new QTcpServer(this);
	//监听并绑定端口
	tcpServer->listen(QHostAddress::Any, 8888);
	
	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(OnConnectTcpServer()));

	connect(ui.sendButton, SIGNAL(clicked()), this, SLOT(OnSendButtonClicked()));

	connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(OnCloseButtonClicked()));

	connect(tcpServer, SIGNAL(disconnected()), this, SLOT(OnDisconnected()));

}

ServerWidget::~ServerWidget()
{
	
}
#include <QDebug>

void ServerWidget::OnConnectTcpServer()
{
	//取出建立好的套接字
	tcpSocket = tcpServer->nextPendingConnection();
	//获取对方的IP和端口号 
	QString ipStr = tcpSocket->peerAddress().toString();

	qint16 portName = tcpSocket->peerPort();

	QString connectStr = QString::fromLocal8Bit("成功连接");
	
	QString tempStr = QString("[%1 : %2]:" + connectStr).arg(ipStr).arg(portName);

	ui.textRead->setText(tempStr);
	 
	connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(OnSeResiveData()));


}

void ServerWidget::OnSendButtonClicked()
{
	if (tcpSocket == NULL)
	{
		return;
	}
	//获取编辑区的内容
	QString str = ui.textWrite->toPlainText();
	//给对方发送数据。使用套接字是tcpSocket
	tcpSocket->write(str.toUtf8().data());

	ui.textWrite->clear();
}
 
void ServerWidget::OnCloseButtonClicked()
{
	if (tcpSocket == NULL)
	{
		return;
	}

	//主动和客户端断开连接
	tcpSocket->disconnectFromHost();
	
	ui.textRead->setText(QString::fromLocal8Bit("连接已断开!!!"));

	tcpSocket = NULL;

}

void ServerWidget::OnSeResiveData()
{
	//从通信套接字中取出内容
	QByteArray dataAll =  tcpSocket->readAll();

	QTextCodec *tc = QTextCodec::codecForName("UTF-8");

	QString str = tc->toUnicode(dataAll);

	ui.textRead->append(str);


}

void ServerWidget::OnDisconnected()
{
	ui.textRead->setText(QString::fromLocal8Bit("连接已断开!!!"));

}



Qt中,可以使用QTcpSocket类来创建TCP客户端。可以通过以下步骤来判断TCP客户端服务端连接状态: 1. 获取QTcpSocket对象的状态:可以使用QAbstractSocket::state()函数来获取QTcpSocket对象的状态,该函数返回一个QAbstractSocket::SocketState枚举类型的值,包括以下状态: - QAbstractSocket::UnconnectedState:未连接状态 - QAbstractSocket::HostLookupState:正在解析主机名 - QAbstractSocket::ConnectingState:正在尝试连接 - QAbstractSocket::ConnectedState:已连接 - QAbstractSocket::BoundState:已绑定 - QAbstractSocket::ClosingState:正在关闭 - QAbstractSocket::ListeningState:正在监听 2. 判断连接状态:通过比较QTcpSocket对象的状态是否为QAbstractSocket::ConnectedState,可以判断TCP客户端是否已连接服务端。代码示例: ```cpp QTcpSocket* tcpSocket = new QTcpSocket(this); // 连接服务端 tcpSocket->connectToHost("127.0.0.1", 8080); if (tcpSocket->state() == QAbstractSocket::ConnectedState) { qDebug() << "TCP客户端连接服务端"; } else { qDebug() << "TCP客户端连接服务端"; } ``` 3. 监听连接状态变化:可以使用QAbstractSocket::stateChanged()信号来监听QTcpSocket对象的状态变化,并在函数槽中进行相应的处理。代码示例: ```cpp QTcpSocket* tcpSocket = new QTcpSocket(this); // 监听连接状态变化 connect(tcpSocket, &QTcpSocket::stateChanged, [=](QAbstractSocket::SocketState state) { if (state == QAbstractSocket::ConnectedState) { qDebug() << "TCP客户端连接服务端"; } else { qDebug() << "TCP客户端连接服务端"; } }); // 连接服务端 tcpSocket->connectToHost("127.0.0.1", 8080); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值