好的,以下是一个基于QT的Windows图形界面聊天程序的算法程序代码。由于实现细节较多,这里只提供框架代码。
#include <QtWidgets>
#include <QtNetwork>
class ChatClient : public QWidget
{
Q_OBJECT
public:
ChatClient(QWidget *parent = nullptr);
private slots:
void sendMessage();
void processMessage();
void displayError(QAbstractSocket::SocketError socketError);
void login();
void logout();
private:
QLabel *hostLabel;
QLineEdit *hostLineEdit;
QLabel *portLabel;
QLineEdit *portLineEdit;
QLabel *userLabel;
QLineEdit *userLineEdit;
QLabel *passwordLabel;
QLineEdit *passwordLineEdit;
QPushButton *loginButton;
QPushButton *logoutButton;
QTextEdit* chatDisplayTextEdit; // 聊天内容显示框
QTextEdit* messageTextEdit; // 消息输入框
QTcpSocket* tcpSocket; // 客户端socket
QString userName; // 用户名
QString password; // 密码
bool isLoggedIn; // 是否已登录
void createLoginDialog(); // 创建登录对话框
};
ChatClient::ChatClient(QWidget *parent)
: QWidget(parent), isLoggedIn(false)
{
// 设置UI控件和布局
hostLabel = new QLabel(tr("Server IP:"));
hostLineEdit = new QLineEdit("127.0.0.1");
portLabel = new QLabel(tr("Port:"));
portLineEdit = new QLineEdit("8888");
userLabel = new QLabel(tr("Username:"));
userLineEdit = new QLineEdit();
passwordLabel = new QLabel(tr("Password:"));
passwordLineEdit = new QLineEdit();
loginButton = new QPushButton(tr("&Login"));
logoutButton = new QPushButton(tr("&Logout"));
logoutButton->setEnabled(false);
QGridLayout* loginLayout = new QGridLayout;
loginLayout->addWidget(hostLabel, 0, 0);
loginLayout->addWidget(hostLineEdit, 0, 1);
loginLayout->addWidget(portLabel, 1, 0);
loginLayout->addWidget(portLineEdit, 1, 1);
loginLayout->addWidget(userLabel, 2, 0);
loginLayout->addWidget(userLineEdit, 2, 1);
loginLayout->addWidget(passwordLabel, 3, 0);
loginLayout->addWidget(passwordLineEdit, 3, 1);
QVBoxLayout* mainLayout = new QVBoxLayout;
mainLayout->addStretch(1);
mainLayout->addSpacing(10);
mainLayout->addLayout(loginLayout);
mainLayout->addSpacing(10);
mainLayout->addWidget(loginButton);
mainLayout->addWidget(logoutButton);
setWindowTitle(tr("Chat Client"));
connect(loginButton, SIGNAL(clicked()), this, SLOT(login()));
connect(logoutButton, SIGNAL(clicked()), this,
SLOT(logout()));
setFixedHeight(sizeHint().height());
}
void ChatClient::login()
{
if (isLoggedIn) // 已登录,不进行操作
return;
QString hostName = hostLineEdit ->text();
int port = portLineEdit ->text().toInt();
userName = userLineEdit ->text();
password = passwordLineEdit ->text();
tcpSocket = new QTcpSocket(this); // 创建socket
connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
this,SLOT(displayError(QAbstractSocket::SocketError)));
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(processMessage()));
tcpSocket ->connectToHost(hostName,port); // 连接到服务器
if(!tcpSocket ->waitForConnected())
{
QMessageBox::warning(this,tr("Connection failed"),tcpSocket ->errorString());
return;
}
isLoggedIn=true; // 设置为已登录
loginButton->setEnabled(false);
logoutButton ->setEnabled(true);
messageTextEdit = new QTextEdit(); // 创建消息输入框
chatDisplayTextEdit = new QTextEdit(); // 创建聊天内容显示框
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(chatDisplayTextEdit);
layout->addWidget(messageTextEdit);
QWidget* widget = new QWidget;
widget->setLayout(layout);
this->layout()->addWidget(widget); // 添加到主界面
}
void ChatClient::logout()
{
if (!isLoggedIn) // 未登录,不进行操作
return;
tcpSocket ->disconnectFromHost(); // 断开连接
isLoggedIn=false; // 设置为未登录
loginButton ->setEnabled(true);
logoutButton ->setEnabled(false);
// 清空控件和布局
delete chatDisplayTextEdit;
delete messageTextEdit;
QLayoutItem *item;
while ((item = layout()->takeAt(2)) != NULL)
{
delete item->widget();
delete item;
}
}
void ChatClient::processMessage()
{
QByteArray data=tcpSocket ->readAll();
QString message=QString(data); // 接收到的数据转成字符串
chatDisplayTextEdit ->append(message); // 在聊天内容显示框中追加消息
}
void ChatClient::displayError(QAbstractSocket::SocketError socketError)
{
switch (socketError)
{
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("Chat Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("Chat Client"),
tr("The connection was refused by the peer. "
"Make sure the chat server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("Chat Client"),
tr("The following error occurred: %1.")
.arg(tcpSocket ->errorString()));
}
}
void ChatClient::sendMessage()
{
if (!isLoggedIn) // 未登录,不进行操作
return;
QString message = messageTextEdit->toPlainText();
if (message.isEmpty()) // 输入框为空,不发送消息
return;
message += "\n"; // 添加换行符
QByteArray data(message.toStdString().c_str(), message.length());
tcpSocket->write(data); // 发送数据到服务器
messageTextEdit->clear(); // 清空输入框
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
ChatClient client;
client.show();
return app.exec();
}
请注意,这只是一个基本的聊天程序示例,并没有实现所有功能或细节。你可以根据自己的需求和项目要求对代码进行修改和扩展。