服务器:
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. how install svn client on MacOS

    how install svn client on MacOS svn https://www.smartsvn.com/downloads/smartsvn/smartsvn-macosx-11_0 ...

  2. P4433 [COCI2009-2010#1] ALADIN

    题目描述 给你 n 个盒子,有 q 个操作,操作有两种: 第一种操作输入格式为"1 L R A B",表示将编号为L到R的盒子里的石头数量变为(X−L+1)×A mod B,其中 ...

  3. Day24-part1-原生Ajax

    参考老师博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html 主要讲了:发数据的3种方式以及上传文件的3种方式.(后续需要总结) 一,原生Aj ...

  4. Java线程Dump分析工具--jstack

    jstack用于打印出给定的java进程ID或core file或远程调试服务的Java堆栈信息,如果是在64位机器上,需要指定选项"-J-d64",Windows的jstack使 ...

  5. git 生成公匙私匙

    直接 ssh-keygen -t rsa -C "*********@qq.com"也行 git config --global user.name “用户名” 用户名随便起!你能 ...

  6. mysql source导入多个sql文件

    mysql>use dbtest; mysql>set names utf8; mysql>source D:/mysql/all.sql; 通过source命令导入多个文件,可以新 ...

  7. 实验一:使用ADO.NET方式读数据

    第一步:创建Asp.net应用程序 在VS中,点击文件->新建->项目,按如图方式选择并输入: 第二步:新建产品浏览网页窗体Listing.aspx: 在项目SportsStoreEx上点 ...

  8. NO.2day 操作系统基础

    操作系统基础 1.为什么要有操作系统 操作系统为用户程序提供一个更好.更简单.更清晰的计算机模型,并管理刚才提到的所有设备(磁盘.内存.显示器.打印机等).程序员无法把所有的硬件操作细节都了解到,管理 ...

  9. linux split 切割大文件

    语法: split  [-l <行数>] [-b <字节>] [-C <字节>] [要切割的目标文件] [输出文件名前缀] 说明: -l <行数> 指定 ...

  10. HDU 2814 斐波那契循环节 欧拉降幂

    一看就是欧拉降幂,问题是怎么求$fib(a^b)$,C给的那么小显然还是要找循环节.数据范围出的很那啥..unsigned long long注意用防爆的乘法 /** @Date : 2017-09- ...