服务器:
incomming
incomming.pro
#-------------------------------------------------
#
# Project created by QtCreator 2016-04-08T09:25:22
#
#------------------------------------------------- QT += core gui
QT +=network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = incomming
TEMPLATE = app SOURCES += main.cpp\
mainwindow.cpp \
myserver.cpp \
socketthread.cpp \
mytcpsocket.cpp HEADERS += mainwindow.h \
myserver.h \
socketthread.h \
mytcpsocket.h FORMS += mainwindow.ui mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H #include <QMainWindow>
class QTcpSocket;
class myserver;
namespace Ui {
class MainWindow;
} class MainWindow : public QMainWindow
{
Q_OBJECT
private:
myserver * server;
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow(); private:
Ui::MainWindow *ui;
}; #endif // MAINWINDOW_H myserver.h
#ifndef MYSERVER
#define MYSERVER
#include<QObject>
#include<QTcpServer>
#include<QWidget>
class myserver :public QTcpServer{
Q_OBJECT
public:
myserver(QWidget * parent);
protected:
virtual void incomingConnection(qintptr socketDescriptor); };
//|定义的结束 必须加;
#endif // MYSERVER mytcpsocket.h
#ifndef MYTCPSOCKET
#define MYTCPSOCKET
#include<QTcpSocket> class mytcpsocket :public QTcpSocket
{
Q_OBJECT
public:
mytcpsocket(QWidget * parent,qintptr p);
private slots:
void on_discon(); public:
void on_connected(); };
#endif // MYTCPSOCKET socketthread.h #ifndef SOCKETTHREAD
#define SOCKETTHREAD
#include<QThread>
#include<QTcpSocket>
#include<QWidget>
class mytcpsocket;
class socketThread :public QThread
{
private:
qintptr ptr;
mytcpsocket * socket;
public:
socketThread(QWidget * parent,qintptr p);
protected:
virtual void run(); };
#endif // SOCKETTHREAD mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"myserver.h"
#include<QHostAddress> MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->server=new myserver(this);
this->server->listen(QHostAddress::LocalHost,520);
} MainWindow::~MainWindow()
{
delete ui;
} myserver.cpp
#include"myserver.h"
#include<QMessageBox>
#include"mytcpsocket.h"
#include"socketthread.h"
myserver::myserver(QWidget * parent):QTcpServer(parent){ }
void myserver::incomingConnection(qintptr socketDescriptor)
{
QMessageBox::about(0,"提示","有新连接");
socketThread * thread=new socketThread(0,socketDescriptor);
thread->start(); /*
mytcpsocket * socket=new mytcpsocket(0,socketDescriptor);
QThread * thread=new QThread();
socket->moveToThread(thread);
thread->start();
*/ } mytcpsocket.cpp
#include"mytcpsocket.h"
#include<QByteArray>
#include<QDataStream>
#include<QString>
#include<QMessageBox>
#include<QDebug>
mytcpsocket::mytcpsocket(QWidget *parent,qintptr p):QTcpSocket(0)
{ //connect(this,SIGNAL(),this,SLOT(on_connected()));
this->setSocketDescriptor(p);
this->on_connected();
this->connect(this,SIGNAL(disconnected()),this,SLOT(on_discon())); }
void mytcpsocket::on_connected()
{ QByteArray arr;
QDataStream dts(&arr,QIODevice::WriteOnly);
dts<<QString("这是数据");
this->write(arr);
//QMessageBox::about(0,"x","发送成功!");
qDebug()<<"发送成功"; }
void mytcpsocket::on_discon()
{
qDebug()<<"有一个客户端断开!";
} socketthread.cpp
#include"socketthread.h"
#include<QString>
#include<QByteArray>
#include<QDataStream>
#include<QMessageBox>
#include<QDebug>
#include"mytcpsocket.h"
socketThread::socketThread(QWidget *parent,qintptr p):QThread(parent)
{ qDebug()<<"QThread构造函数依然在 旧线程";
this->ptr=p;
} void socketThread::run(){ /*1.QObject->moveToThread(Thread *)会把一个Qt对象移动到一个新线程中运行 默认在run()中调用了 exec()这样 run()执行完后不会
* 直接关闭 线程 还会让它 进入消息循环 直到调用了 结束 槽
* 2.QtcpSocket 的write()函数是异步的 也就是 调用了 后不会立即 发送数据,它会直接往下执行 直到run()的尾部,如果run()没有
* 调用exec()进行消息循环等待,那么 这个线程 直接就结束了,不会再发送。(发送数据失败)
*3.如果在run()中调用了 exec()(发送成功)
*4.如果在 write(QByteArray);后面加一句 socket->waitForBytesWritten();这里就会阻塞等待 直到数据开始发送,这样
* 不需要exec()在 线程结束之前直接就发送完了
*socket->waitForConnected()
* socket->waitForDisconnected()
* socket->waitForReadyRead()都是一个道理
*/
qDebug()<<"开始新线程";
/* QTcpSocket * socket=new QTcpSocket();
socket->setSocketDescriptor(this->ptr); QByteArray arr;
QDataStream dts(&arr,QIODevice::WriteOnly);
dts<<QString("这是数据");
socket->write(arr);
*/
mytcpsocket * socket=new mytcpsocket(0,this->ptr);
socket->waitForBytesWritten();
// this->exec();
/*
1. 连接服务器
m_tcpSocket->connectToHost("127.0.0.1", 9877);
connected = m_tcpSocket->waitForConnected();
只有使用waitForConnected()后,QTcpSocket才真正尝试连接服务器,并返回是否连接的结果。 2. 写数据
m_tcpSocket->write(str.toStdString().c_str(), strlen(str.toStdString().c_str()));
m_tcpSocket->waitForBytesWritten();
当使用waitForBytesWritten()后,QTcpSocket才真正发送数据。
m_tcpSocket->write(str1.toStdString().c_str(), strlen(str1.toStdString().c_str()));
m_tcpSocket->write(str2.toStdString().c_str(), strlen(str2.toStdString().c_str()));
的结果是发送了str1str2 3. 断开与服务器的连接
m_tcpSocket->disconnectFromHost()
m_tcpSocket->waitForDisconnected() 4. 善于使用QTcpSocket的SIGNAL:connected(), disconnected(), error(QAbstractSocket::SocketError)
配合自定义私有开关变量bool connected, QTimer
可以实现自动重连接等逻辑。 */
} main.cpp
#include "mainwindow.h"
#include <QApplication> int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show(); return a.exec();
} /***********************/ 客户端
useincomming
useincomming.pro
#-------------------------------------------------
#
# Project created by QtCreator 2016-04-08T09:36:28
#
#------------------------------------------------- QT += core gui
QT +=network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = useincomming
TEMPLATE = app SOURCES += main.cpp\
mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H #include <QMainWindow>
class QTcpSocket;
namespace Ui {
class MainWindow;
} class MainWindow : public QMainWindow
{
Q_OBJECT public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
QTcpSocket * socket;
private:
Ui::MainWindow *ui;
private slots:
void on_readyread();
void on_conn();
}; #endif // MAINWINDOW_H mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QTcpSocket>
#include<QHostAddress>
#include<QString>
#include<QByteArray>
#include<QDataStream>
#include<QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->socket=new QTcpSocket(this);
this->socket->connectToHost(QHostAddress::LocalHost,520);
connect(this->socket,SIGNAL(connected()),this,SLOT(on_conn()));
connect(this->socket,SIGNAL(readyRead()),this,SLOT(on_readyread()));
} MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_readyread()
{
QMessageBox::about(this,"提示","开始接受");
QByteArray array=this->socket->readAll();
QDataStream dts(&array,QIODevice::ReadOnly);
QString data;
dts>>data;
QMessageBox::about(this,"提示",data); }
void MainWindow::on_conn()
{
QMessageBox::about(this,"提示","连接成功");
} main.cpp
#include "mainwindow.h"
#include <QApplication> int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show(); return a.exec();
}

C++ Qt多线程 TcpSocket服务器实例的更多相关文章

  1. Qt封装QTcpServer参考资料--QT4中构建多线程的服务器

    首先说一下对多线程这个名词的理解过程.以前听说过很多次多线程这个词,而且往往与服务器联系起来,因此一直把多线程误解为服务器特有的功能:直到这次课程设计,仔细学习了一下多线程的机制,才知道真正的意思.简 ...

  2. 对Qt下对话服务器客户端的总结(MyTcpServer与MyTcpClient)

    在汇文培训老师给讲了这个例子.讲的挺好的 Qt编写聊天服务器与客户端主要用到下面两个类: QTcpSocket --- 处理连接的 QTcpServer --- 处理服务器,对接入进行响应,创建每个链 ...

  3. (转载)关于java多线程web服务器 以及相关资料转载

    1.自己实现的简单的java多线程web服务器: https://blog.csdn.net/chongshangyunxiao321/article/details/51095149 自己实现一个简 ...

  4. Qt 多线程同步与通信

    Qt 多线程同步与通信 1 多线程同步 Qt提供了以下几个类来完成这一点:QMutex.QMutexLocker.QSemphore.QWaitCondition. 当然可能还包含QReadWrite ...

  5. 【QT】 Qt多线程的“那些事”

    目录 一.前言 二.QThread源码浅析 2.1 QThread类的定义源码 2.2 QThread::start()源码 2.3 QThreadPrivate::start()源码 2.4 QTh ...

  6. 1.QT多线程使用小结

    开头 一个进程可以有一个或更多线程同时运行.线程可以看做是"轻量级进程",进程完全由操作系统管理,线程即可以由操作系统管理,也可以由应用程序管理. Qt 使用QThread来管理线 ...

  7. 非域环境下搭建自动故障转移镜像无法将 ALTER DATABASE 命令发送到远程服务器实例的解决办法

    非域环境下搭建自动故障转移镜像无法将 ALTER DATABASE 命令发送到远程服务器实例的解决办法 环境:非域环境 因为是自动故障转移,需要加入见证,事务安全模式是,强安全FULL模式 做到最后一 ...

  8. 7、provider: SQL 网络接口, error: 26 - 定位指定的服务器/实例时出错

    在建立与服务器的连接时出错.在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败.(provider: SQL 网络接口, error ...

  9. SQLServer2012在登录远程服务器实例时报错:尝试读取或写入受保护的内存

    SQLServer2012在登录远程服务器实例时报错:尝试读取或写入受保护的内存.这通常指示其它内存已损坏.(System.Data). 而登录本地数据库实例则能顺利登入,不存在上述问题. 试一试重置 ...

随机推荐

  1. CKEditor 4 & markdown & rich text editor

    CKEditor 4 ckeditor 4 http://ckeditor.com

  2. Spring(1):Spring简介

    一句话概括: Spring是一种轻量级控制反转IoC和面向切面AOP的容器框架 初衷: 使用接口编程而不是类 为javabean提供一个更好的应用配置框架 javabean是一种规范而不是技术.是指符 ...

  3. 触发Full GC执行的情况 以及其它补充信息

    除直接调用System.gc外,触发Full GC执行的情况有如下四种.1. 旧生代空间不足旧生代空间只有在新生代对象转入及创建为大对象.大数组时才会出现不足的现象,当执行Full GC后空间仍然不足 ...

  4. python selenium2 定位一组元素find_elements实例

    打开hao123首页,需要定位以上区域中的所有链接,他们有相同的父元素<ul class="js_bd site-bd site-hd0">,所有链接处在li>a ...

  5. Oracle 修改dmp的表空间

    1.百度下载  UltraEdit 并安装 2.打开程序,文件-->打开-->找到dmp  文件太大会提示,选择第一个默认,确定 3.按CTRL+H 转成十六进制编辑 4.例如:dmp里面 ...

  6. MT【147】又见最大最小

    (2018浙江省赛12题)设$a\in R$,且对任意的实数$b$均有$\max\limits_{x\in[0,1]}|x^2+ax+b|\ge1$求$a$的范围_____解答:由题意$\min\li ...

  7. 控制对象的创建方式(禁止创建栈对象or堆对象)和创建的数量

    我们知道,C++将内存划分为三个逻辑区域:堆.栈和静态存储区.既然如此,我称位于它们之中的对象分别为堆对象,栈对象以及静态对象.通常情况下,对象创建在堆上还是在栈上,创建多少个,这都是没有限制的.但是 ...

  8. 【堆的启发式合并】【P5290】[十二省联考2019]春节十二响

    Description 给定一棵 \(n\) 个节点的树,点有点权,将树的节点划分成多个集合,满足集合的并集是树的点集,最小化每个集合最大点权之和. Limitation \(1~\leq~n~\le ...

  9. Jenkins(四)---Jenkins添加密钥对

    一.添加密钥 1.添加git用户和git密码对 ,用于git客户端从gitlab上拉取代码到本地 /** lihaibo 文章内容都是根据自己工作情况实践得出. *版权声明:本博客欢迎转发,但请保留原 ...

  10. win10不能被远程解决方案(开启远程桌面,防火墙仍不能被远程解决方案)

    开启远程桌面,防火墙仍不能被远程解决方案 1.“Win+R”→“gpedit.msc” 2.依次展开“计算机配置”→“管理模版”→“系统”→“凭据分配”→找到“允许分配保存的凭据用于仅NTLM服务器身 ...