您的位置:首页 > 理论基础 > 计算机网络

基于tcp和qt的简单聊天室搭建

2016-08-10 18:48 405 查看
使用Qt库中的 <QTcpServer>  和<QTcpSocket>类实现局域网络下的聊天室。

分为服务端和客户端;

服务端接收来自各个客户端的信息,并发送到所有客户端;

客户端用于用户登陆及聊天。

客户端:

使用<QTcpSocket>类即可;

tcp_client.h
namespace Ui {
class tcp_cilent;
}

class tcp_cilent : public QWidget
{
Q_OBJECT

public:
explicit tcp_cilent(QWidget *parent = 0);
~tcp_cilent();

private slots:
void on_pushButtonconnect_clicked();

void on_send_clicked();
void slotConnected();
void slotDisconnected();
void slotError(QAbstractSocket::SocketError);
void slotStateChanged(QAbstractSocket::SocketState);
void slotReadData();
//bool isconnect;
private:
Ui::tcp_cilent *ui;
QTcpSocket*tcpsocket;

};tcp_client.cpp
tcp_cilent::tcp_cilent(QWidget *parent):
QWidget(parent),
ui(new Ui::tcp_cilent)
{
ui->setupUi(this);
ui->send->setDisabled(true);
ui->lineEditsend->setDisabled(true);
//isconnect=false;
}
tcp_cilent::~tcp_cilent()
{
delete ui;
}

void tcp_cilent::on_pushButtonconnect_clicked()
{

tcpsocket=new QTcpSocket(this);
connect(tcpsocket,SIGNAL(connected()),this,SLOT(slotConnected()));
connect(tcpsocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
connect(tcpsocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slotError(QAbstractSocket::SocketError)));
connect(tcpsocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(slotStateChanged(QAbstractSocket::SocketState)));
connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(slotReadData()));

QHostAddress host(ui->LineEdithost->text());
tcpsocket->connectToHost(host,ui->lineEditport->text().toShort());

//isconnect=true;
// ui->pushButtonconnect->setText("close");

/* else
{
isconnect=false;
ui->pushButtonconnect->setText("connect");
}*/
}

void tcp_cilent::slotReadData()
{
while(tcpsocket->bytesAvailable()>0)
{
QByteArray ba;
ba.resize(tcpsocket->bytesAvailable());
tcpsocket->read(ba.data(),ba.size());
ui->listWidget->addItem(QString(ba));
ui->listWidget->scrollToBottom();
}
}

void tcp_cilent::slotConnected()
{
//isconnect=true;
ui->send->setDisabled(false);
ui->lineEditsend->setDisabled(false);
}

void tcp_cilent::slotDisconnected()
{
//isconnect=false;
qDebug()<<"connecttion lost\n";
ui->send->setDisabled(true);
ui->lineEditsend->setDisabled(true);
}

void tcp_cilent::slotError(QAbstractSocket::SocketError err)
{
qDebug()<<"error"<<err;
}

void tcp_cilent::slotStateChanged(QAbstractSocket::SocketState s)
{

qDebug()<<"state"<<s;
}

void tcp_cilent::on_send_clicked()
{
tcpsocket->write(ui->user->text().toUtf8()+": "+ui->lineEditsend->text().toUtf8());
ui->lineEditsend->clear();
}


服务器端

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QObject>
#include<QTcpSocket>
class MyTcpSocket : public QTcpSocket
{
Q_OBJECT
public:
MyTcpSocket(QObject*parent=0);
~MyTcpSocket();
signals:
void disconnected(MyTcpSocket*);
void updateMsg(QByteArray);
private slots:
void slotDisconnected();
void slotReadData();
};

#endif // MYTCPSOCKET_H
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  QT TCP