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

使用Qt库中的   和类实现局域网络下的聊天室。

分为服务端和客户端;

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

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

客户端:

使用类即可;

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"<write(ui->user->text().toUtf8()+": "+ui->lineEditsend->text().toUtf8());
    ui->lineEditsend->clear();
}

服务器端


#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include 
#include
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)