QTcpServer简单用法

   我们都知道TCP是面向流的,连接的可靠传输协议。QTcpServer就是基于TCP协议的服务端。它调用listen() 方法进行监听客户端的连接,建立连接之后便可以进行通信。以下是简单的demo。 
 

服务器代码

 
 
class TCPServer: public QObject
{
	Q_OBJECT
public:
	TCPServer(QObject *parent = NULL);
	~TCPServer();
	
	void star();
	void close();

protected slots:
	void newConnectSlot();
	void showReceiptMessageSlot();
private:
	QTcpServer              *m_pServer;
};


TCPServer::TCPServer(QObject *parent /* = NULL */):QObject(parent)
{

}

TCPServer::~TCPServer()
{

}

void TCPServer::star()
{
	m_pServer = new QTcpServer();
	m_pServer->listen(QHostAddress::Any,8888);
	connect(m_pServer,SIGNAL(newConnection ()),this,SLOT(newConnectSlot()));
	cout<<"Server Running ......"<<endl;
}

void TCPServer::close()
{
	m_pServer->close();
}

void TCPServer::newConnectSlot()
{
	QTcpSocket *pSocket = m_pServer->nextPendingConnection();
	m_SocketVec.push_back(pSocket);
	connect(pSocket,SIGNAL(readyRead()),this,SLOT(showReceiptMessageSlot()));
}

void TCPServer::showReceiptMessageSlot()
{
	QTcpSocket *pSenderSocket = qobject_cast<QTcpSocket*>(sender());
	QByteArray mesArray = pSenderSocket->readAll();
	string strMes(mesArray);
	std::cout<<strMes<<endl;
	pSenderSocket->write("hi,welcome...");    //回发给客户端的消息

}
客户端代码

class Client : public QDialog
{
	Q_OBJECT

public:
	Client(QWidget *parent = 0, Qt::WFlags flags = 0);
	~Client();

private slots:
	void sendMessageClickSlot();
	void showReceiveMessageSlot();
private:
	QTcpSocket     *m_pSocket;

	QLabel         *m_pRecieveMesLbl;
	QLabel         *m_pMessageLbl;
	QLineEdit      *m_pMessageLEdit;
	QPushButton    *m_pSendMesBtn;

};

Client::Client(QWidget *parent, Qt::WFlags flags)
	: QDialog(parent, flags)
{
	m_pMessageLbl = new QLabel(tr("Message:"),this);
	m_pMessageLEdit = new QLineEdit(this);
	m_pSendMesBtn = new QPushButton(tr("Sending"),this);
	m_pSocket = new QTcpSocket();
	m_pRecieveMesLbl = new QLabel(this);
	m_pRecieveMesLbl->setGeometry(5,30,200,20);
	m_pMessageLbl->setGeometry(5,5,100,20);
	m_pMessageLEdit->setGeometry(110,5,100,20);
	m_pSendMesBtn->setGeometry(220,5,50,20);
	m_pSocket->connectToHost(QHostAddress::LocalHost,8888);
	connect(m_pSendMesBtn,SIGNAL(clicked()),this,SLOT(sendMessageClickSlot()));
	connect(m_pSocket,SIGNAL(readyRead()),this,SLOT(showReceiveMessageSlot()));
	//ui.setupUi(this);
}

Client::~Client()
{

}


void Client::sendMessageClickSlot()
{
	QString text = m_pMessageLEdit->text();
	m_pSocket->write(text.toLocal8Bit());

}

void Client::showReceiveMessageSlot()
{
	QByteArray mesArray = m_pSocket->readAll();
	QString strMes(mesArray);
	m_pRecieveMesLbl->setText(tr(mesArray.constData()));
}

结果截图

QTcpServer简单用法_第1张图片


你可能感兴趣的:(qt)