- 论坛徽章:
- 0
|
chatsever.h
===============================
#ifndef CHATSEVER_H
#define CHATSEVER_H
#include <QMainWindow>
#include<QIcon>
#include<QTcpServer>
#include<QTcpSocket>
#include<QByteArray>
#include<QDebug>
namespace Ui {
class ChatSever;
}
class ChatSever : public QMainWindow
{
Q_OBJECT
public:
explicit ChatSever(QWidget *parent = 0);
~ChatSever();
void startSever();
void stopSever();
private slots:
void on_startBtn_clicked();
void on_stopBtn_clicked();
//处理网络客户端连接的槽函数
void newConnectionSlots();
//客户端数据
void clientReadyReadSlots();
private:
Ui::ChatSever *ui;
QTcpServer* server;
QTcpSocket* socket;
};
#endif // CHATSEVER_H
=================================
chatsever.cpp
================================
#include "chatsever.h"
#include "ui_chatsever.h"
ChatSever::ChatSever(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ChatSever)
{
ui->setupUi(this);
ui->startBtn->setIcon(QIcon("D:\\Qt-appli\\ChatSever\\icons\\u.png" );
}
ChatSever::~ChatSever()
{
delete ui;
}
void ChatSever::startSever()
{
//
}
void ChatSever::stopSever()
{
disconnect(server,SIGNAL(newConnection()));
server->close();
}
void ChatSever: n_startBtn_clicked()
{
//启动服务器
//1.得到相应的ip,port
//IPv4_Any
int port=ui->lineEdit->text().toInt();
ui->textEdit->append(tr("%1" .arg(port));
//2.实例化服务器对象
server = new QTcpServer(this);
//3.启动监听
connect(server,SIGNAL(newConnection()),this,SLOT(newConnectionSlots()));
// server->listen(QHostAddress::Any,port);
//4.等待处理客户端连接
server->listen(QHostAddress::Any,10000);
//connect(server,SIGNAL(newConnection()),this,SLOT(newConnectionSlots()));
ui->textEdit->append("listen ..." ;
}
void ChatSever: n_stopBtn_clicked()
{
//
}
void ChatSever::newConnectionSlots()
{
ui->textEdit->append("this is a client ..." ;
socket=server->nextPendingConnection();
connect(socket,SIGNAL(readyRead()),this,SLOT(clientReadyReadSlots()));
}
void ChatSever::clientReadyReadSlots()
{
QByteArray data;
data.clear();
while(socket->bytesAvailable()){
data.append(socket->readAll());
}
ui->textEdit->append("ready read" ;
ui->textEdit->append(data);
} |
|