server:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent) , ui(new Ui::Widget)
{
ui->setupUi(this);
//实例化通信套接字和监听套接字
tcpServer = new QTcpServer(this);
tcpSocket = new QTcpSocket(this);
//有新连接的,就获得其socket
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_slot()));
}
//获取socket
void Widget::newConnection_slot()
{
//接收来自客户端的通信套接字对象
tcpSocket = tcpServer->nextPendingConnection();
//显示已经连接
ui->recvEdits->appendPlainText("有新的连接");
//获得socket以后,准备开始读
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyReads_Slot()));
}
void Widget::readyReads_Slot()
{
QString buf;
buf = tcpSocket->readAll();
ui->recvEdits->appendPlainText(buf);
}
//建立连接按钮
void Widget::on_openBts_clicked()
{
//监听来自客户端的连接
tcpServer->listen(QHostAddress::Any,ui->portEdits->text().toUInt());
}
void Widget::on_closeBts_clicked()
{
tcpServer->close();
}
void Widget::on_sendBts_clicked()
{
tcpSocket->write(ui->sendEdits->text().toLocal8Bit().data());
//清空发送框里面的内容
ui->sendEdits->clear();
}
client:
#include "client.h"
#include "ui_client.h"
client::client(QWidget *parent) :
QWidget(parent),
ui(new Ui::client)
{
ui->setupUi(this);
//通信套接字
tcpclient = new QTcpSocket(this);
}
void client::on_openBt_clicked()
{
//连接服务器
tcpclient->connectToHost(ui->ipEdit->text(),ui->portEdit->text().toUInt());
connect(tcpclient,SIGNAL(connected()),this,SLOT(connected_slot()));
}
void client::connected_slot()
{
connect(tcpclient,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
}
//显示从服务器发来的内容
void client::readyRead_slot()
{
ui->recvEdit->appendPlainText(tcpclient->readAll());
}
void client::on_closeBt_clicked()
{
tcpclient->close();
}
//发送数据给服务器
void client::on_sendBt_clicked()
{
tcpclient->write(ui->sendEdit->text().toLocal8Bit().data());
ui->sendEdit->clear();
}