Widget::Widget(QWidget *parent)
socket = new QTcpSocket(this);
connect(socket,&QTcpSocket::connected,this,&Widget::connected_slot);
connect(socket,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
connect(socket,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
void Widget::on_connectBtn_clicked()
userName = ui -> usernameEdit -> text();
QString hostName = ui -> ipEdit -> text();
quint16 port = ui -> portEdit ->text().toUInt();
socket -> connectToHost(hostName,port);
ui ->ipEdit -> setEnabled(false);
ui ->portEdit -> setEnabled(false);
ui ->connectBtn -> setEnabled(false);
ui ->usernameEdit -> setEnabled(false);
void Widget::connected_slot(){
QMessageBox::information(this,"成功","连接服务器成功");
QString msg = userName +"进入聊天室";
socket -> write(msg.toLocal8Bit());
void Widget::readyRead_slot(){
QByteArray msg = socket ->readAll();
ui -> msgList -> addItem(QString::fromLocal8Bit(msg));
void Widget::on_sendBtn_clicked()
QString m = ui ->msgEdit ->text();
QString msg = userName + ":"+m;
socket -> write(msg.toLocal8Bit());
ui -> msgEdit -> clear();
void Widget::on_disConnectBtn_clicked()
QString msg = userName + ":离开聊天室";
socket -> write(msg.toLocal8Bit());
socket -> disconnectFromHost();
ui ->ipEdit -> setEnabled(true);
ui ->portEdit -> setEnabled(true);
ui ->connectBtn -> setEnabled(true);
ui ->usernameEdit -> setEnabled(true);
void Widget::disconnected_slot(){
QMessageBox::information(this,"退出","断开成功");