Qt网络编程
Qt提供了Socket的支持,它采用API形式的封装,使得程序员不需要接触底层的代码就可以对socket进行操作。
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会保持这个连接,直到通信结束。
获取途径书籍