服务器端
//服务器端需要两种套接字
QTcpServer *tcpServer;//监听套接字
QTcpSocket *tcpSocket;//通信套接字
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowTitle("服务器端");
tcpServer = new QTcpServer(this); //指定父对象
tcpServer->listen(QHostAddress::Any, 8888); //监听套接字 地址+端口
connect(tcpServer, &QTcpServer::newConnection,//等待客户端的连接请求
[=]()
{
tcpSocket = tcpServer->nextPendingConnection();//取出通信套接字
QHostAddress hostip = tcpSocket->peerAddress();
quint16 hostport = tcpSocket->peerPort();
QString str=QString("[%1:%2] connect").arg(hostip.toString()).arg(hostport);
ui->textEditread->setText(str);//显示连接成功信息
//显示客服端发送的信息
connect(tcpSocket,&QTcpSocket::readyRead,//只要通信套接字中有内容就调用readyread函数
[=]()
{
QByteArray array = tcpSocket->readAll();
ui->textEditread->append(array.data());
}
);
}
);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_SendButton_clicked()
{
QString str= ui->textEditwrite->toPlainText();
//将服务器端的信息发送出去
tcpSocket->write(str.toUtf8().data());
}
void Widget::on_CloseButton_clicked()
{
//tcpServer->disconnect();
tcpSocket->disconnectFromHost();
tcpSocket->close();
}
客户端
//客户端只需要通信套接字
QTcpSocket *tcpSocket;
Client::Client(QWidget *parent) :
QWidget(parent),
ui(new Ui::Client)
{
ui->setupUi(this);
setWindowTitle("Client");
tcpSocket = new QTcpSocket(this);
connect(tcpSocket,&QTcpSocket::connected,//判断连接请求是否成功
[=]()
{
ui->textEditRead->setText("与服务器链接成功");
}
);
//接收服务器发送过来的数据
connect(tcpSocket,&QTcpSocket::readyRead,
[=]()
{
QByteArray array = tcpSocket->readAll();
ui->textEditRead->append(array);
}
);
}
Client::~Client()
{
delete ui;
}
void Client::on_ConnectButton_clicked()
{
//客户端首先发送连接请求
QString ip=ui->lineEditIP->text();
quint16 port = ui->lineEditPort->text().toInt();
tcpSocket->connectToHost(QHostAddress(ip),port);//向服务器发送链接请求
}
void Client::on_SendButton_clicked()//向服务器端发送消息
{
QString str = ui->textEditWrite->toPlainText();
tcpSocket->write(str.toUtf8().data());//字符串只能先转utf8才能再转char*
}
void Client::on_CloseButton_clicked()
{
tcpSocket->disconnectFromHost();
tcpSocket->close();
}