java UDP通訊客戶端與伺服器端例項分析
阿新 • • 發佈:2020-01-21
本文例項講述了java UDP通訊客戶端與伺服器端。分享給大家供大家參考,具體如下:
最初Udp是以位元組為單位進行傳輸的,所以有很大的限制
伺服器端:
import java.net.*; public class TestUdpServer { public static void main(String[] args) throws Exception { byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); // try { DatagramSocket ds = new DatagramSocket(2345); while(true) { ds.receive(dp); System.out.println(new String(buf,dp.getLength())); // } // } catch (Exception e) { // e.printStackTrace(); } } }
使用者端:
import java.net.*; public class TestUdpClient { public static void main(String[] args) throws Exception { byte[] buf = new byte[1024]; buf = (new String("hello")).getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",2345)); // try { DatagramSocket ds = new DatagramSocket(5679); ds.send(dp); ds.close(); // } catch (Exception e) { // e.printStackTrace(); // } } }
注:由於必須以位元組為單位進行傳輸,Udp的傳輸用了一個容器類的東西,用來接收位元組
先建一個位元組陣列,然後以這個陣列建立容器。用來傳輸資料。
例項:傳輸一個Long型別的資料
伺服器端:
import java.io.*; import java.net.*; public class UdpServer { public static void main(String[] args) throws Exception { byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); DatagramSocket ds = new DatagramSocket(2345); while(true) { ByteArrayInputStream is = new ByteArrayInputStream(buf); DataInputStream dis = new DataInputStream(is); ds.receive(dp); System.out.println(dis.readLong()); } } }
使用者端:
import java.io.*; import java.net.*; public class UdpClient { public static void main(String[] args) throws Exception { Long n = 10000L; ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeLong(n); byte[] buf = new byte[1024]; buf = os.toByteArray(); System.out.println(buf.length); DatagramPacket dp = new DatagramPacket(buf,2345)); DatagramSocket ds = new DatagramSocket(5679); ds.send(dp); ds.close(); } }
注:由於Udp是以位元組為單位進行傳輸的,所以要用到ByteArray的輸入和輸出流用來進行資料的轉換。
另外,相較於Output流,Input流在構建的時候需要一個數組作為引數,用來存放資料。
在基本的Udp傳輸的基礎上,程式碼分為兩部分,一部分是把傳輸或接受的Long型別資料轉換為byte型別的資料,然後是基本的資料傳輸。
另一方面,直接的位元組流不能轉換為Long型別,同理,剛接收的資料是位元組型別,直接列印(System.out.println)是以字串型別輸出的,都需要通過Data的資料流進行轉換。
更多關於java相關內容感興趣的讀者可檢視本站專題:《Java Socket程式設計技巧總結》、《Java檔案與目錄操作技巧彙總》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》和《Java快取操作技巧彙總》
希望本文所述對大家java程式設計有所幫助。