• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
七喜不加冰
努力努力再努力
博客园    首页    新随笔    联系   管理    订阅  订阅
socket qt基础版本
.h
#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication1.h"
#include <QtNetwork/QtNetwork>
#include <iostream>
class QtGuiApplication1 : public QMainWindow
{
    Q_OBJECT

public:
    QtGuiApplication1(QWidget *parent = Q_NULLPTR);

    QTcpServer* server;
    QTcpSocket* client_connection;
public slots:
void read_new_connection();
void read_data();
private:
    Ui::QtGuiApplication1Class ui;


};
.cpp
#include "QtGuiApplication1.h"
//QtServer
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    server = new QTcpServer;
    server->listen(QHostAddress::Any, 6665);
    connect(server, SIGNAL(newConnection()), this, SLOT(read_new_connection()));
}

void QtGuiApplication1::read_new_connection()
{
    client_connection = new QTcpSocket;
    
    client_connection = server->nextPendingConnection();
    //qDebug() << client_connection->socketDescriptor;
    std::cout << "connect success!" << std::endl;
    connect(client_connection, SIGNAL(readyRead()), this, SLOT(read_data()));
}

void QtGuiApplication1::read_data()
{
    QString str = client_connection->read(100);
    std::cout << str.toStdString() << std::endl;
//    std::cout << client_connection->peerName().toStdString() << std::endl;
    
}

 

posted on 2020-03-28 08:37  七喜不加冰  阅读(154)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3