Qt网络编程
2015-06-16 20:45
573 查看
Qt提供了Socket的支持,它采用API形式的封装,使得程序员不需要接触底层的代码就可以对socket进行操作。
1.UDP的实现
UDP不是连接协议,没有客户端与服务端的概念。
1)建立套接字相关对象
2)初始化套接字相关对象
3)定义实现响应slot
4)关联套接字的signal和接收slot。
5)发送字符串
2.TCP的实现
TCP的实现与UDP的实现大同小异,它是面向连接的协议。
1)服务端
1>套接字对象的定义
2>套接字的初始化
3>响应连接
4>接收信息slot与UDP是一样的
2)客户端的实现
获取途径书籍
1.UDP的实现
UDP不是连接协议,没有客户端与服务端的概念。
1)建立套接字相关对象
1 QSocketDevice *MUReceiveSocket;//套接字对象 2 3 QSocketNotifier *MSocketNotifier;//套接字监听对象
2)初始化套接字相关对象
1 MUReceiveSocket = new QSocketDevice(QSocketDevice::Datagram); 2 3 //UDP初始化 4 5 QHostAddress MyAddress; 6 7 QString FakeAddress; 8 9 FakeAddress = get_eth1_ip(); 10 11 //取得接口IP 12 13 MyAddress。setAddress(FakeAddress); 14 15 MUReceiveSocket->bind(MyAddress,port); 16 17 //绑定到指定网络接口地址(IP),指定逻辑端口 18 19 MSocketNotifier = new QSocketNotifier(MUReceiveSocket->socket(),QSocketNotifier::Read,0,"MSocketNotifier"); 20 21 //监听MUReceiveSocket套接字 22 23
3)定义实现响应slot
1 virtual void OnMReceive(); 2 3 void Client::OnMReceive() 4 5 { 6 7 int ByteCount,ReadCount; 8 9 char *IncomingChar; 10 11 fprintf(stderr,"Load a piece of Message!\n"); 12 13 ByteCount = MUReceiveSocket->bytesAvailable(); 14 15 InconingChar = (char *)malloc(ByteCount + 1); 16 17 ReadCount = MUReceiveSocket->readBlock(IncomingChar,ByteCount); 18 19 IncomingChar[ByteCount] = '\0'; 20 21 fprintf(stderr,"%s",IncomingChar); 22 23 } 24 25
4)关联套接字的signal和接收slot。
1 connect(MSocketNotifier,SIGNAL(activated(int)),this,SLOT(OnMReceive())); 2 3 //当MSocketNotifier检测到MUReceiveSocket活跃时调用OnMReceive 4 5
5)发送字符串
1 char information[20]; 2 3 strcpy(information,"abc"); 4 5 MUReceiveSocket->writeBlock(information,length,MyAddress,2201);
2.TCP的实现
TCP的实现与UDP的实现大同小异,它是面向连接的协议。
1)服务端
1>套接字对象的定义
1 QSSocket *ServerSocket; 2 3 QSocketDevice *ClientSocket; 4 5 QSocketNotifier *ClientNotifier; 6 7 QSocketNotifier *ServerNotifier;
2>套接字的初始化
1 QHostAddress MyAddress; 2 3 QString FakeAddress; 4 5 FakeAddress = "127.0.0.1"; 6 7 MyAddress。setAddress(FakeAddress); 8 9 UINT Port = 1234; 10 11 ServerSocket = new QSSocket(MyAddress,Port,this,0); 12 13 //指定监听地址及端口 14 15 ClientSocket = new QSocketDevice(QSocketDevice::Stream); 16 17 ClientNotifier = new QSocketNotifier(ClientSocket->socket(),QSocketNotifier::Read,0,"ClientSocket");
3>响应连接
1 只需要在QSSocket的构造函数里添加如下代码。 2 3 Server Socket->new Connection(ClientSocket->socket()); 4 5 当受到客户端的连接后,ClientSocket会自动响应,并接收连接。
4>接收信息slot与UDP是一样的
2)客户端的实现
1 客户端的实现与UDP实现不同之处是客户端套接字不需要bind端口,因为连接上服务器端后TCP会保持这个连接,直到通信结束。
获取途径书籍
相关文章推荐
- Qt之QLineEdit之插入图标及位置设置
- Qt学习笔记002 2015/6/16
- QT stylesheet 操作
- Qt中的pro文件配置总结
- QTP中Web系统常用对象类型列举
- Ubuntu下安装Qt全部过程
- Qt开发ActiveX及环境搭建
- QT项目升级(QT4.6.3到QT5.2)时,遇到的问题和解决方法
- 又写了一个pyqt4的小工具主要用来学习
- QTP中WinApp常用对象类型列举
- Pyqt 国际化多语言支持
- Qt属性表控件的使用 QtTreePropertyBrowser
- 怎样VS2013下安装Qt5的插件
- Qt Creator 黑色主题配置
- QT 画图工具QWT 和 QwtPolar在windows和linux下的编译安装
- Qt数据库 QSqlTableModel实例操作
- MQTT IM开发
- Qt QLineEdit 限制输入类型以及大小Int 和double
- VS2010/VS2012/VS2013+QT5编程之开发环境配置
- qt数据库总结