udp客户端 Java_java UDP通信客户端与服务器端实例分析
本文實例講述了java UDP通信客戶端與服務(wù)器端。分享給大家供大家參考,具體如下:
最初Udp是以字節(jié)為單位進(jìn)行傳輸?shù)?#xff0c;所以有很大的限制
服務(wù)器端:
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,0,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();
// }
}
}
注:由于必須以字節(jié)為單位進(jìn)行傳輸,Udp的傳輸用了一個容器類的東西,用來接收字節(jié)
先建一個字節(jié)數(shù)組,然后以這個數(shù)組創(chuàng)建容器。用來傳輸數(shù)據(jù)。
實例:傳輸一個Long類型的數(shù)據(jù)
服務(wù)器端:
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,buf.length,
new InetSocketAddress("127.0.0.1",2345));
DatagramSocket ds = new DatagramSocket(5679);
ds.send(dp);
ds.close();
}
}
注:由于Udp是以字節(jié)為單位進(jìn)行傳輸?shù)?#xff0c;所以要用到ByteArray的輸入和輸出流用來進(jìn)行數(shù)據(jù)的轉(zhuǎn)換。
另外,相較于Output流,Input流在構(gòu)建的時候需要一個數(shù)組作為參數(shù),用來存放數(shù)據(jù)。
在基本的Udp傳輸?shù)幕A(chǔ)上,代碼分為兩部分,一部分是把傳輸或接受的Long類型數(shù)據(jù)轉(zhuǎn)換為byte類型的數(shù)據(jù),然后是基本的數(shù)據(jù)傳輸。
另一方面,直接的字節(jié)流不能轉(zhuǎn)換為Long類型,同理,剛接收的數(shù)據(jù)是字節(jié)類型,直接打印(System.out.println)是以字符串類型輸出的,都需要通過Data的數(shù)據(jù)流進(jìn)行轉(zhuǎn)換。
希望本文所述對大家java程序設(shè)計有所幫助。
總結(jié)
以上是生活随笔為你收集整理的udp客户端 Java_java UDP通信客户端与服务器端实例分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [html] 在HTML5中,用于获得
- 下一篇: java美元兑换,(Java实现) 美元