操作系統:ARM-LINUX
QT版本:QT-2.3.2-FOR-LINUX
GUI:Qtopia
在LINUX 下進行網絡編程,我們可以使用LINUX提供的統一的套接字接口。但是這種方法牽涉到太多的結構體,比如IP地址,端口轉換等,不熟練的人往往容易犯這樣那樣的錯誤。QT中提供的SOCKET完全使用了類的封裝機制,使用戶不需要接觸底層的各種結構體操作。而且它採用QT本身的signal-slot機制,使編寫的程序更容易理解。
QT中共提供四個與套按字相關的類,分別是:
QServerSocket:TCP-based server
QSocket: Buffered TCP connection
QSocketDevice: Platform-independent low-level socket API
QSocketNotifier: Support for socket callbacks
下面介紹使用QT進行網絡編程,我們使用一個簡單的C/S模式網絡程序說明如何使用QT中的套接字。同時我們用TCP和UDP兩種協議實現這個程序(該程序客戶端與服務端各向對方發送一個字符口串“abc”)
1、UDP實現
UDP是不連接協議,沒有客戶端與服務端的概念。
1)建立套接字相關對象
QSocketDevice *MUReceiveSocket; //套接字對象
QSocketNotifier *MSocketNotifier; //套接字監聽對象
2)初始化套接字相關對象
MUReceiveSocket=new QSocketDevice(QSocketDevice::Datagram);
//UDP初始化
QHostAddress MyAddress;
QString FakeAddress;
FakeAddress = get_eth1_ip(); //取得接口IP
MyAddress.setAddress(FakeAddress);
MUReceiveSocket->bind(MyAddress,Port);
//綁定到指定網絡接口地址(IP),指定邏輯端口
MSocketNotifier = new QSocketNotifier(MUReceiveSocket->socket(),QSocketNotifier::Read,0,"MSocketNotifier");
//監聽MUReceiveSocket套接字
3)定義用實現響應slot
virtual void OnMReceive();
void Client::OnMReceive()
{
int ByteCount,ReadCount;
char *IncommingChar;
fprintf(stderr,"Load a piece of Message!/n");
ByteCount=MUReceiveSocket->bytesAvailable();
IncommingChar=(char *)malloc(ByteCount+1);
ReadCount=MUReceiveSocket->readBlock(IncommingChar,ByteCount);
IncommingChar[ByteCount]='/0';
fprintf(stderr,“%s“,IncommingChar); //打印接收的字符串
}
4)關聯套接字的signal和接收slot
connect(MSocketNotifier,SIGNAL(activated(int)),this,SLOT(OnMReceive()));
//當MSocketNotifier檢測到MUReceiveSocket活躍時調用OnMReceive
5)發送字符串
char information[20];
strcpy(information,“abc“);
MUReceiveSocket->writeBlock(information,length,MyAddress,2201);
2、TCP實現
TCP的實現與UDP的實現大同小異,它是面象連接的協議。這裏只介紹與UDP不同的地方。
服務端:
1)套接字對象的定義
比UDP多定義一個套接字,一個用來監聽端口,一個用來通信。
QSocketDevice *ServerSocket;
QSocketDevice *ClientSocket;
QSocketNotifier *ClientNotifier;
QSocketNotifier *ServerNotifier;
2)套接字的初始化
QHostAddress MyAddress;
QString FakeAddress;
FakeAddress = "127.0.0.1";
MyAddress.setAddress(FakeAddress);
UINT Port=1234;
ServerSocket=new QSocketDevice(QSocketDevice::Stream);
ClientSocket=new QSocketDevice(QSocketDevice::Stream);
ServerSocket->bind(MyAddress,Port);
ServerSocket->listen(20); //20代表所允許的最大連接數
ClienttNotifier = new QSocketNotifier(ClientSocket->socket(),QSocketNotifier::Read,0,"ClientSocket");
ServerNotifier = new QSocketNotifier(ServerSocket->socket(),QSocketNotifier::Read,0,"ServerSocket");
3)響應連接(在定義slot中響應)
當收到客戶端的連接後,響應它,並以ClientSocket接收:
ServerSocket->SetSocket(ClientSocket->socket());
4)接收信息slot與UDP一致,這裏不在敘述。
客戶端實現:
客戶端的實現與UDP實現大同小異,不同的地方只是客戶端套接字不需要bind端口,因爲連接上服 務端後TCP會保持這個連接,直到通信的結束。
QT中的SOCKET編程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.