Java UDP資料報和Socket

2021-08-25 06:57:01 字數 2653 閱讀 2213

兩個核心類datagrampacket 資料報、datagramsocket 資料報socket

接收資料報的建構函式

public datagrampacket(byte buf, int length)

傳送資料報的建構函式,比接收的多了傳送目標位址

public datagrampacket(byte buf, int length, inetaddress address, int port)

兩個核心方法 datagramsocket類

public void send(datagrampacket p) throws ioexception

public synchronized void receive(datagrampacket p) throws ioexception

都是void的,傳送和接受到的資料被包裝到datagrampacket中。

一些有用的應用程式

//簡單udp客戶端,傳送空資料到伺服器,列印接收資訊

public class ******udpclient

public ******udpclient(inetaddress host, int port) throws socketexception

public byte request() catch (ioexception e)

return in.getdata();

}public static void main(string args) catch (exception e) catch (unknownhostexception e1)

}try catch (unsupportedencodingexception e)

system.out.println(result);

} catch (exception e)

}}

//可重用的udpserver,繼承類根據接收資訊傳送返回結果,

//要實現public abstract void response(datagrampacket request)方法

public abstract class baseudpserver extends thread

public baseudpserver(int port) throws socketexception

public void run() catch (ioexception e) }}

public abstract void response(datagrampacket request);

}//繼承baseudpserver的,實現了daytime協議的server

public class daytimeserver extends baseudpserver

public void response(datagrampacket request) catch (unsupportedencodingexception e) catch (ioexception e)

}public static void main(string args) catch (socketexception e)

}}

echo協議

基於tcp的echo客戶端,可以傳送乙個訊息,然後在同乙個連線上等待響應。但是基於udp的echo客戶端不能保證傳送的訊息總能被收到。因此要非同步地傳送和接受資料。

public class udpechoserver extends udpserver 

public void respond(datagrampacket packet) catch (ioexception ex)

}public static void main(string args) catch (socketexception ex) }}

public class udpechoclient

try catch (socketexception e) catch (unknownhostexception e) }}

public class senderthread extends thread

public void halt()

public void run() catch (ioexception e)

thread.yield();}}

}public class receiverthread extends thread

public receiverthread(datagramsocket socket)

public void run() catch (ioexception ex) }}

}public abstract class udpserver extends thread

public udpserver(int port) throws socketexception

public void run() catch (ioexception ex)

} // end while

} // end run

public abstract void respond(datagrampacket request);

}

資料報和資料報間的聯絡和差別

請先參看文章後邊pdu的定義 datagram 資料報 在 網路層中的傳輸單元 例如ip 乙個datagram可能被壓縮成乙個或幾個packets,在資料鏈路層中傳輸。packet 資料報 封裝 和傳輸 的基本單元,它穿越網路層和資料鏈路層的分解面。通常乙個packet對映成乙個frame,但也有例...

HTTP請求資料報和響應資料報的結構

請求資料報結構 一 請求行 請求行在請求資料報的第一行,包含請求型別 get post 請求資源路徑 協議的版本和型別。二 訊息頭 若干訊息頭樣式 w3c定義的一些有特殊意義的鍵值對 如content type text html,charset utf 8等,伺服器端和客戶端都會遵循訊息頭的約定,...

資料報格式 USB資料報解析

由域構成的包有四種型別,分別是令牌包 資料報 握手包和特殊包,前面三種是重要的包,不同包的域結構不同,介紹如下 1 令牌包 分為輸入包 輸出包 設定包和幀起始包 注意這裡的輸入包是用於設定輸入命令的,輸出包是用來設定輸出命令的,而不是放資料的 其中輸入包 輸出包和設定包的格式都是一樣的 sync p...