1
新建一个项目:TCPServer.pro


修改TCPServer.pro,注意:如果是想使用网络库,需要加上network

SOURCES
+=
\

TcpServer.cpp
\

TcpClient.cpp

HEADERS
+=
\

TcpServer.h
\

TcpClient.h

QT
+=
gui widgets
network

CONFIG
+=
C++11

B
新建如下文件,因为要用到网络库,所以加上network

C
编写IP选择下拉选,头文件ChooseInterface.h

#ifndef
CHOOSEINTERFACE_H

#define
CHOOSEINTERFACE_H

#include
<QDialog>

#include
<QComboBox>

class
ChooseInterface
:
public
QDialog

{

Q_OBJECT

public:

explicit
ChooseInterface(QWidget
*parent
);

QComboBox*
_comboBox;

QString
_strSelect;

signals:

public
slots:

void
slotComboBoxChange(QString);

};

#endif
//
CHOOSEINTERFACE_H

编写ChooseInterface.cpp

#include
"ChooseInterface.h"

#include
<QNetworkInterface>

#include
<QVBoxLayout>

ChooseInterface::ChooseInterface(QWidget
*parent)
:

QDialog(parent)

{

/*
get
all
interface
*/

QList<QHostAddress>
addrList
=
QNetworkInterface::allAddresses();

#if
0

QList<QNetworkInterface>
infList =
QNetworkInterface::allInterfaces();

QList<QNetworkAddressEntry>
entryList =
infList).addressEntries();

entryList).broadcast()

#endif

//编写一个下拉选

_comboBox
=
new
QComboBox;

QVBoxLayout*
lay
=
new
QVBoxLayout(this);

lay->addWidget(_comboBox);

foreach(QHostAddress
addr,
addrList)

{

//将地址都转换成为ipv4的地址

quint32
ipaddr
=
addr.toIPv4Address();

//的ip

if(ipaddr
==
0)

continue;

//在comboBox中添加下拉选

_comboBox->addItem(QHostAddress(ipaddr).toString());

}

//当下拉选发生变化时的操作

connect(_comboBox,
SIGNAL(currentIndexChanged(QString)),

this,
SLOT(slotComboBoxChange(QString)));

}

void
ChooseInterface::slotComboBoxChange(QString
str)

{

this->_strSelect
=
str;

}

上面的运行结果是:

编写TcpServer.h

#ifndef
TCPSERVER_H

#define
TCPSERVER_H

#include
<QWidget>

#include
<QTcpServer>

#include
<QTcpSocket>

#include
<QTextBrowser>

class
TcpServer:public
QWidget

{

Q_OBJECT

public:

explicit
TcpServer(QWidget
*parent
);

QTcpServer*
_server;

QTcpSocket*
_socket;

QTextBrowser*
_show;

signals:

public
slots:

void
slotNetConnection();

void
slotReadyRead();

};

#endif
//
TCPSERVER_H

编写TcpServer.cpp

#include
"TcpServer.h"

#include
<QHBoxLayout>

#include
<QNetworkInterface>

#include
<QMessageBox>

#include
"ChooseInterface.h"

TcpServer::TcpServer(QWidget
*parent)
:

QWidget(parent)

{

//
创建服务器并监听

_server
=
new
QTcpServer;

ChooseInterface
dlg;

dlg.exec();

//消息提示框

QMessageBox::information(NULL,"you
select
the
ip:",
dlg._strSelect);

_server->listen(QHostAddress(dlg._strSelect),
9988);

//
当有客户端来连接时,调用slotNetConnection方法

connect(_server,
SIGNAL(newConnection()),

this,
SLOT(slotNetConnection()));

_show
=
new
QTextBrowser;

QHBoxLayout*
lay
=
new
QHBoxLayout(this);

lay->addWidget(_show);

}

void
TcpServer::slotNetConnection()

{

//
判断是否有未处理的连接

while(_server->hasPendingConnections())

{

//
调用nextPeddingConnection去获得连接的socket

_socket
=
_server->nextPendingConnection();

_show->append("New
connection
....");

//
为新的socket提供槽函数,来接收数据

connect(_socket,
SIGNAL(readyRead()),

this,
SLOT(slotReadyRead()));

}

}

void
TcpServer::slotReadyRead()

{

//
接收数据,判断是否有数据,如果有,通过readAll函数获取所有数据

while(_socket->bytesAvailable()
>
0)

{

_show->append("Data
arrived
.....
");

QByteArray
buf
=
_socket->readAll();

_show->append(buf);

}

}

编写TcpClient.h

#ifndef
TCPCLIENT_H

#define
TCPCLIENT_H

#include
<QWidget>

#include
<QTcpSocket>

#include
<QLineEdit>

class
TcpClient:public
QWidget

{

Q_OBJECT

public:

explicit
TcpClient(QWidget
*parent
);

QTcpSocket*
_socket;

QLineEdit*
_lineEdit;

signals:

public
slots:

void
slotButtonClick();

};

#endif
//
TCPCLIENT_H

编写TcpClient.cpp

#include
"TcpClient.h"

#include
<QHBoxLayout>

#include
<QPushButton>

TcpClient::TcpClient(QWidget
*parent):

QWidget(parent)

{

_socket
=
new
QTcpSocket(this);

_socket->connectToHost("127.0.0.1",
9988);

_lineEdit
=
new
QLineEdit;

QHBoxLayout*
lay
=
new
QHBoxLayout(this);

lay->addWidget(_lineEdit);

QPushButton*
button
=
new
QPushButton("Send");

lay->addWidget(button);

connect(button,
SIGNAL(clicked()),
this,
SLOT(slotButtonClick()));

connect(_lineEdit,
SIGNAL(returnPressed()),
this,
SLOT(slotButtonClick()));

}

void
TcpClient::slotButtonClick()

{

QString
strText
=
_lineEdit->text();

if(strText.isEmpty())

return;

_socket->write(strText.toUtf8());

_lineEdit->clear();

}

MyWidget.h

#ifndef
MYWIDGET_H

#define
MYWIDGET_H

#include
<QWidget>

class
MyWidget
:
public
QWidget

{

Q_OBJECT

public:

explicit
MyWidget(QWidget
*parent
);

signals:

public
slots:

};

#endif
//
MYWIDGET_H

MyWidget.cpp

#include
"MyWidget.h"

#include
<QApplication>

#include
"TcpServer.h"

#include
"TcpClient.h"

MyWidget::MyWidget(QWidget
*parent)
:

QWidget(parent)

{

}

int
main(int
argc,char**
argv)

{

QApplication
app(argc,argv);

TcpServer
s;
s.show();

TcpClient
c;
c.show();

s.setWindowTitle("server");

c.setWindowTitle("client");

return
app.exec();

}

运行结果:


编写UDP程序

UDPServer.pro

QT
+=
gui widgets
network

CONFIG
+=
C++11

HEADERS
+=
\

Udp1.h
\

Udp2.h
\

MyWidget.h

SOURCES
+=
\

Udp1.cpp
\

Udp2.cpp
\

MyWidget.cpp

Udp1.h

#ifndef
UDP1_H

#define
UDP1_H

#include
<QWidget>

#include
<QUdpSocket>

class
Udp1
:
public
QWidget

{

Q_OBJECT

public:

explicit
Udp1(QWidget
*parent
);

QUdpSocket*
_udp;

signals:

public
slots:

void
slotReadyRead();

};

#endif
//
UDP1_H

Udp1.cpp

#include
"udp1.h"

#include
<QTimer>

#include
<QDateTime>

Udp1::Udp1(QWidget
*parent)
:

QWidget(parent)

{

//
创建udpsocket,并连接槽函数,用来接收数据

_udp
=
new
QUdpSocket;

_udp->bind(10001);

connect(_udp,
SIGNAL(readyRead()),

this,
SLOT(slotReadyRead()));

//
使用定时器来定时发送时间戳

QTimer*
timer
=
new
QTimer;

timer->setInterval(1000);

timer->start();

connect(timer,
&QTimer::timeout,
[&](){

quint64
timestamp
=
QDateTime::currentMSecsSinceEpoch();

QString
str
=
QString::number(timestamp);

#if
0

//
普通UDPsocket发送

_udp->writeDatagram(str.toUtf8(),
QHostAddress("127.0.0.1"),
);

#else

//
广播发送,注意:QHostAddress::Broadcast是255.255.255.255,
192.168.6.255

//  
_udp->writeDatagram(str.toUtf8(),
QHostAddress::Broadcast,
10002);

//
multicast,
224.0.0.1~224.0.0.255
is
multicast
address
of
LAN

_udp->writeDatagram(str.toUtf8(),
QHostAddress("224.0.0.131"),
10002);

#endif

});

}

void
Udp1::slotReadyRead()

{

while(_udp->hasPendingDatagrams())

{

quint32
datagramSize
=
_udp->pendingDatagramSize();

QByteArray
buf(datagramSize,
0);

_udp->readDatagram(buf.data(),
buf.size());

qDebug()
<<"Udp1"<<
buf;

}

}

Udp2.h

#ifndef
UDP2_H

#define
UDP2_H

#include
<QWidget>

#include
<QUdpSocket>

class
Udp2
:
public
QWidget

{

Q_OBJECT

public:

explicit
Udp2(QWidget
*parent
);

QUdpSocket*
_udp;

signals:

public
slots:

void
slotReadyRead();

};

#endif
//
UDP2_H

Udp2.cpp

#include
"udp2.h"

#include
<QTimer>

#include
<QDateTime>

#include
<QLineEdit>

Udp2::Udp2(QWidget
*parent)
:

QWidget(parent)

{

_udp
=
new
QUdpSocket;

//
the
address
of
bind
and
multicast
must
be
same
tpye(IPV4
or
IPV6)

_udp->bind(QHostAddress::AnyIPv4,
10002);

//
join
the
multicast
address
(224.0.0.131)
for
recv
mulicast
package

_udp->joinMulticastGroup(QHostAddress("224.0.0.131"));

connect(_udp,
SIGNAL(readyRead()),

this,
SLOT(slotReadyRead()));

QTimer*
timer
=
new
QTimer(this);

timer->setInterval(1000);

timer->start();

connect(timer,
&QTimer::timeout,
[&](){

quint64
timestamp
=
QDateTime::currentMSecsSinceEpoch();

QString
str
=
QString::number(timestamp);

_udp->writeDatagram(str.toUtf8(),
QHostAddress("127.0.0.1"),
10001);

});

}

void
Udp2::slotReadyRead()

{

while(_udp->hasPendingDatagrams())

{

quint32
datagramSize
=
_udp->pendingDatagramSize();

QByteArray
buf(datagramSize,
0);

_udp->readDatagram(buf.data(),
buf.size());

qDebug()
<<
"Udp2"
<<buf;

}

}

运行结果:

控制台输出结果如下:

5.关于QT中的网络编程,QTcpSocket,QUdpSocket的更多相关文章

  1. Qt 多线程和网络编程学习

    一,Qt多线程类学习 QThread类,开始一个新的线程就是开始执行重新实现QThread::run(),run()是默认现实调用exec(),QThread::start()开始线程的执行,run( ...

  2. QT中的SOCKET编程(QT-2.3.2)

    转自:http://mylovejsj.blog.163.com/blog/static/38673975200892010842865/ QT中的SOCKET编程 2008-10-07 23:13 ...

  3. Qt学习之网络编程(一)

    一些说明 学了有一段时间的python了,小项目做了不少,最近由于项目需要,所以要回归老本行了,开始重点突击C++和qt.python的网络爬虫系列有时间就更吧. 获取本机网络信息 在网络应用中,经常 ...

  4. QT中的SOCKET编程

    转自:http://mylovejsj.blog.163.com/blog/static/38673975200892010842865/ QT中的SOCKET编程 2008-10-07 23:13 ...

  5. 网游中的网络编程系列1:UDP vs. TCP

    原文:UDP vs. TCP,作者是Glenn Fiedler,专注于游戏网络编程相关工作多年. 目录 网游中的网络编程系列1:UDP vs. TCP 网游中的网络编程2:发送和接收数据包 网游中的网 ...

  6. 网游中的网络编程3:在UDP上建立虚拟连接

    目录 网游中的网络编程系列1:UDP vs. TCP 网游中的网络编程2:发送和接收数据包 网游中的网络编程3:在UDP上建立虚拟连接 TODO 二.在UDP上建立虚拟连接 介绍 UDP是无连接的,一 ...

  7. 第84节:Java中的网络编程(中)

    第84节:Java中的网络编程(中) 实现客户端和服务端的通信: 客户端需要的操作,创建socket,明确地址和端口,进行键盘录入,获取需要的数据,然后将录入的数据发送给服务端,为socket输出流, ...

  8. 第78节:Java中的网络编程(上)

    第78节:Java中的网络编程(上) 前言 网络编程涉及ip,端口,协议,tcp和udp的了解,和对socket通信的网络细节. 网络编程 OSI开放系统互连 网络编程指IO加网络 TCP/IP模型: ...

  9. 第62节:探索Java中的网络编程技术

    前言 感谢! 承蒙关照~ 探索Java中的网络编程技术 网络编程就是io技术和网络技术的结合,网络模型的定义,只要共用网络模型就可以两者连接.网络模型参考. 一座塔有七层,我们需要闯关. 第一层物理层 ...

随机推荐

  1. [Codeforces 864F]Cities Excursions

    Description There are n cities in Berland. Some pairs of them are connected with m directed roads. O ...

  2. [USACO13OPEN]照片Photo

    题目描述 Farmer John has decided to assemble a panoramic photo of a lineup of his N cows (1 <= N < ...

  3. ●洛谷P3242 [HNOI2015]接水果

    题链: https://www.luogu.org/problemnew/show/P3242 题解: 整体二分,扫描线+树状数组. 详细的题解:http://blog.csdn.net/thy_as ...

  4. SpringCloud学习之soa基础

    一.soa简单介绍 1)面向服务的架构(SOA)是一个组件模型,它将应用程序的不同功能单元(称为服务)通过这些服务之间定义良好的接口和契约联系起来.SOA是解决复杂业务模块,提高扩展性,维护性,可伸缩 ...

  5. .net4.0设计模式(一)使用Lazy的单例模式

    延迟加载,亦称延迟实例化,延迟初始化等, 主要表达的思想是,把对象的创建将会延迟到使用时创建,而不是在对象实例化时创建对象,即用时才加载.这种方式有助于提高于应用程序的性能,避免浪费计算,节省内存的使 ...

  6. JVM基础

    1.基础 JDK  将java文件编译成class文件 JRE   包含JVM JVM可以进行内存管理 利用JDK(调用JAVA API)开发了属于我们自己的JAVA程序后,通过JDK中的编译程序(j ...

  7. lgp20151222 java中如何将Object类型转换为int类型

    if (object instanceof Integer) {    Integer.parseInt(object.toString()); } 很简单是不是?我就想提醒下自己,java有个特殊词 ...

  8. 安装插件出现eclipse An internal error occurred during: "Installing Software". xxxxxxxxx

    就是你自己本来就有那个插件了 百度怎么删吧.... 看一下我这个文章 强烈建议本地安装的时候用第四种安装 http://www.cnblogs.com/ydymz/articles/7203260.h ...

  9. vue mint-ui 实现省市区街道4级联动(仿淘宝京东收货地址4级联动)

    demo及源码地址 https://github.com/artiely/citypicker 先去下载一个“省份.城市.区县.乡镇” 四级联动数据,然后 引入 import { Picker } f ...

  10. FastReport报表MVC显示步骤

    FastReport报表MVC使用步骤如下: 1.创建MVC网站项目 最终DEMO如下图所示 2.引用相关DLL FastReport.dll FastReport.Web.dll 3.Web.con ...