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! "); 12 13 ByteCount = MUReceiveSocket->bytesAvailable(); 14 15 InconingChar = (char *)malloc(ByteCount + 1); 16 17 ReadCount = MUReceiveSocket->readBlock(IncomingChar,ByteCount); 18 19 IncomingChar[ByteCount] = '