UDP通訊的簡單實現(程式)

2021-06-06 18:13:15 字數 2331 閱讀 2430

資訊處理介面,定義了資訊的關閉,傳送,和接收

public inte***ce messageaction

udp類實現了messageaction封裝了下面的資訊,並提供了相應的get和set方法

private int sendport;// 要傳送資料的埠號埠號

private int localport;// 本機埠號

inetaddress address = null;// 位址資訊

datagramsocket socket = null;

datagrampacket receivepacket = null;// 接收用的資料報

datagrampacket sendpacket = null;// 傳送資料報

byte bytestosend = new byte[255];// 要傳送的位元組陣列

構造器如下

public udp(int sendport, inetaddress address, datagramsocket socket,

byte bytestosend)

public udp(inetaddress address, datagramsocket socket, byte bytestosend)

public udp(int sendport, int localport, inetaddress address,

datagramsocket socket, datagrampacket receivepacket,

datagrampacket sendpacket, byte bytestosend)

public udp()

sendmessage和receivemessage方法的實現如下

/**

* 傳送資料報

*/@override

public void sendmessage() catch (ioexception e)

} /**

* 接收資料報,把接收到的資料放入位元組陣列buf中,因為一般而言,

* 需要呼叫getoffset()和getdata()方法來訪問剛接收到的資料

* 如果直接呼叫getdata()方法,該方法總是返回位元組陣列的原始大小,忽略了

* 實際資料的內部偏移量和長度資訊,所以用到了buf來處理資訊

*/@override

public void receivemessage() catch (ioexception e)

} @override

public void close()

下面是udp的具體的子類udpclient和udpserver的具體的實現

public class udpclient extends udp 

public udpclient(inetaddress address, datagramsocket socket,

byte bytestosend)

public udpclient(int sendport, inetaddress address, datagramsocket socket,

byte bytestosend)

public udpclient(int sendport, int localport, inetaddress address,

datagramsocket socket, datagrampacket receivepacket,

datagrampacket sendpacket, byte bytestosend)

public static void main(string args) throws unknownhostexception, socketexception

}

udpserver

public class udpserver extends udp 

public udpserver(inetaddress address, datagramsocket socket,

byte bytestosend)

public udpserver()

public udpserver(int port, inetaddress address, datagramsocket socket,

byte bytestosend)

}

在myeclipse裡先執行udpserver在執行udpclient,檢查程式結果便可

Python 實現udp簡單通訊

學習 指路 server端 匯入socket import socket 設定埠號,主機號 port 12345 host 將上面倆放在位址裡 addr host,port 為該物件繫結固定位址 ip,埠號 server socket.bind addr while true recvfrom 表示...

python實現UDP程式通訊

一 1 接收端 import socket 使用ipv4協議,使用udp協議傳輸資料 s socket.socket socket.af inet,socket.sock dgram 繫結埠和埠號,空字串表示本機任何可用ip位址 s.bind 5000 while true data,addr s....

udp簡單通訊

客戶端 include include include include include define serv port 8000 int main int argc,char ar close sockfd return 0 如何實現內網和外網的通訊 main.c udpserver create...