導航:首頁 > 編程語言 > java實現udp

java實現udp

發布時間:2022-08-20 09:12:46

❶ 5 java 如何使用udp協議傳送文件

//發送端SocketSendFile.java
import java.io.*;
import java.net.*;

public class SocketSendFile {
public static final int SER_PORT=666;
public static final int CLI_PORT=8484;
public static final String SER_IP="192.168.0.35";
public static int bufSize = 1024;
public static byte] mess = new bytebufSize];
//建立Socket引用
public static DatagramSocket dp;

public static void main(String] args) throws Exception {
dp = new DatagramSocket(SER_PORT);
//調用構造函數SocketSendFile,並傳遞參數args0](所要傳輸的文件名)
SocketSendFile(args0]);
}

public static void SocketSendFile(String file2) throws Exception {
//定義一個計數器
int pos =0;
//設置寫入流
FileInputStream fis = new FileInputStream(file2);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);

int i;
do {
i = dis.read();
int j=0;
while (j<1024 & i != -1) {
messpos++] = (byte) i;
i=dis.read();
j++;
}
dp.send(new DatagramPacket(mess,pos,InetAddress.getByName(SER_IP),CLI_PORT));
}
while (i != -1);
fis.close();
}
}

//接收端SocketReceiveFile.java
import java.net.*;
import java.io.*;

public class SocketReceiveFile {
public static int bufSize=1024;
public static byte] mess=new bytebufSize];
public static DatagramSocket dp;
public static final int SER_PORT=8484;

public static void main(String] args) throws Exception {
dp = new DatagramSocket(SER_PORT);
SocketReceiveFile(args0]);
}

public static void SocketReceiveFile(String file1) throws Exception {
FileOutputStream fos = new FileOutputStream(file1);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);

int i;
DatagramPacket p = new DatagramPacket(mess,mess.length);

while(true) {
boolean j=false;
while (p.getData().length != 0) {
dos.write(p.getData());
dp.receive(p);
j=true;
}
// System.out.println(new String(p.getData(),0,p.getLength()));
if (j)
System.out.println("文件傳送完畢.");
}
// fos.close();
}
}

❷ Java寫的一個udp的demo用來計算探針傳送過來的數據,怎麼實現一個介面來調用這個數據

Java UDP通信簡單實現
1、Java實現方式
1)server端



/**
*UDPserver端
**/
publicclassUdpServer{
//定義一些常量
privatefinalintMAX_LENGTH=1024;//最大接收位元組長度
privatefinalintPORT_NUM=5066;//port號
//用以存放接收數據的位元組數組
privatebyte[]receMsgs=newbyte[MAX_LENGTH];
//數據報套接字
;
//用以接收數據報
;

publicUdpServer(){
try{
/*******接收數據流程**/
//創建一個數據報套接字,並將其綁定到指定port上
datagramSocket=newDatagramSocket(PORT_NUM);
//DatagramPacket(bytebuf[],intlength),建立一個位元組數組來接收UDP包
datagramPacket=newDatagramPacket(receMsgs,receMsgs.length);
//receive()來等待接收UDP數據報
datagramSocket.receive(datagramPacket);

/******解析數據報****/
StringreceStr=newString(datagramPacket.getData(),0,datagramPacket.getLength());
System.out.println("ServerRece:"+receStr);
System.out.println("ServerPort:"+datagramPacket.getPort());

/*****返回ACK消息數據報*/
//組裝數據報
byte[]buf="Ireceivethemessage".getBytes();
DatagramPacketsendPacket=newDatagramPacket(buf,buf.length,datagramPacket.getAddress(),datagramPacket.getPort());
//發送消息
datagramSocket.send(sendPacket);
}catch(SocketExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//關閉socket
if(datagramSocket!=null){
datagramSocket.close();
}
}
}
}

2)client


/***
*UDPclientClient端
***/
publicclassUdpClient{

privateStringsendStr="SendString";
privateStringnetAddress="127.0.0.1";
privatefinalintPORT_NUM=5066;

;
;

publicUdpClient(){
try{

/***發送數據***/
//初始化datagramSocket,注意與前面Server端實現的差別
datagramSocket=newDatagramSocket();
//使用DatagramPacket(bytebuf[],intlength,InetAddressaddress,intport)函數組裝發送UDP數據報
byte[]buf=sendStr.getBytes();
InetAddressaddress=InetAddress.getByName(netAddress);
datagramPacket=newDatagramPacket(buf,buf.length,address,PORT_NUM);
//發送數據
datagramSocket.send(datagramPacket);

/***接收數據***/
byte[]receBuf=newbyte[1024];
DatagramPacketrecePacket=newDatagramPacket(receBuf,receBuf.length);
datagramSocket.receive(recePacket);

StringreceStr=newString(recePacket.getData(),0,recePacket.getLength());
System.out.println("ClientReceAck:"+receStr);
System.out.println(recePacket.getPort());


}catch(SocketExceptione){
e.printStackTrace();
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//關閉socket
if(datagramSocket!=null){
datagramSocket.close();
}
}
}
}

❸ java怎麼實現JSON打包UDP

java實現JSON打包UDP cJSON支持在C程序中創建和解析JSON數據,其提供多種方法供C程序使用,最直接的是將cJSON.c和cJSON.h加入到C工程中

(1) QJsonObject用於在Qt中創建JSON對象

(2)數據傳輸通過UDP運行

❹ Java語言中如何使用UDP協議進行數據傳輸的

java里UDP協議傳送的方式細節已經封裝了到類DatagramSocket里了,只要用DatagramSocket的對象進行傳輸數據就可以了.

底層實現是應該依靠本地C語言程序來完成的

❺ Java語言應用中實現UDP協議編程的方法

java UDP主要用到了DatagramSocket和DatagramPacket兩個類。
DatagramSocket類表示用來發送和接收數據報包的套接字。
數據報套接字是包投遞服務的發送或接收點。每個在數據報套接字上發送或接收的包都是單獨編址和路由的。從一台機器發送到另一台機器的多個包可能選擇不同的路由,也可能按不同的順序到達。

DatagramPacket類表示數據報包。
數據報包用來實現無連接包投遞服務。每條報文僅根據該包中包含的信息從一台機器路由到另一台機器。從一台機器發送到另一台機器的多個包可能選擇不同的路由,也可能按不同的順序到達。不對包投遞做出保證。

建議看下API

❻ java 中怎麼使用UDP

發送步驟:

使用 DatagramSocket(int port) 建立socket(套間字)服務。

將數據打包到DatagramPacket中去

通過socket服務發送 (send()方法)

關閉資源

importjava.io.IOException;
importjava.net.*;

publicclassSend{

publicstaticvoidmain(String[]args){

DatagramSocketds=null;//建立套間字udpsocket服務

try{
ds=newDatagramSocket(8999);//實例化套間字,指定自己的port
}catch(SocketExceptione){
System.out.println("Cannotopenport!");
System.exit(1);
}

byte[]buf="Hello,Iamsender!".getBytes();//數據
InetAddressdestination=null;
try{
destination=InetAddress.getByName("192.168.1.5");//需要發送的地址
}catch(UnknownHostExceptione){
System.out.println("Cannotopenfindhost!");
System.exit(1);
}
DatagramPacketdp=
newDatagramPacket(buf,buf.length,destination,10000);
//打包到DatagramPacket類型中(DatagramSocket的send()方法接受此類,注意10000是接受地址的埠,不同於自己的埠!)

try{
ds.send(dp);//發送數據
}catch(IOExceptione){
}
ds.close();
}
}

接收步驟:

使用 DatagramSocket(int port) 建立socket(套間字)服務。(我們注意到此服務即可以接收,又可以發送),port指定監視接受埠。

定義一個數據包(DatagramPacket),儲存接收到的數據,使用其中的方法提取傳送的內容

通過DatagramSocket 的receive方法將接受到的數據存入上面定義的包中

使用DatagramPacket的方法,提取數據。

關閉資源。

importjava.net.*;

publicclassRec{

publicstaticvoidmain(String[]args)throwsException{

DatagramSocketds=newDatagramSocket(10000);//定義服務,監視埠上面的發送埠,注意不是send本身埠

byte[]buf=newbyte[1024];//接受內容的大小,注意不要溢出

DatagramPacketdp=newDatagramPacket(buf,0,buf.length);//定義一個接收的包

ds.receive(dp);//將接受內容封裝到包中

Stringdata=newString(dp.getData(),0,dp.getLength());//利用getData()方法取出內容

System.out.println(data);//列印內容

ds.close();//關閉資源
}
}

❼ Java如何實現UDP自動回復

發送步驟:
使用 DatagramSocket(int port) 建立socket(套間字)服務。
將數據打包到DatagramPacket中去
通過socket服務發送 (send()方法)
關閉資源

import java.io.IOException; import java.net.*; public class Send { public static void main(String[] args) { DatagramSocket ds = null; //建立套間字udpsocket服務 try { ds = new DatagramSocket(8999); //實例化套間字,指定自己的port } catch (SocketException e) { System.out.println("Cannot open port!"); System.exit(1); } byte[] buf= "Hello, I am sender!".getBytes(); //數據 InetAddress destination = null ; try { destination = InetAddress.getByName("192.168.1.5"); //需要發送的地址 } catch (UnknownHostException e) { System.out.println("Cannot open findhost!"); System.exit(1); } DatagramPacket dp = new DatagramPacket(buf, buf.length, destination , 10000); //打包到DatagramPacket類型中(DatagramSocket的send()方法接受此類,注意10000是接受地址的埠,不同於自己的埠!) try { ds.send(dp); //發送數據 } catch (IOException e) { } ds.close(); } }

接收步驟:
使用 DatagramSocket(int port) 建立socket(套間字)服務。(我們注意到此服務即可以接收,又可以發送),port指定監視接受埠。
定義一個數據包(DatagramPacket),儲存接收到的數據,使用其中的方法提取傳送的內容
通過DatagramSocket 的receive方法將接受到的數據存入上面定義的包中
使用DatagramPacket的方法,提取數據。

❽ java中UDP文件傳輸怎麼實現

java UDP連接,如果要發送文件的話,你只能自己定義一系列的協議
因為TCP UDP 雙方發送都是二進制數據
那麼這個實現非常復雜
得不停的發送數據,寫數據,建議使用http協議

❾ 用java實現UDP校驗和計算

public static void main(String[] arg) {
String str = "hello";
System.out.println(toByte(str));
// 得到結果:byte[] sbytes = { 0X68, 0X65, 0X6c, 0X6c, 0X6f };
}

private static String toByte(String str) {
byte[] bytes = str.getBytes();
StringBuffer sb = new StringBuffer();
sb.append("byte[] sbytes = { ");
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("0X%s", Integer.toHexString(bytes[i])));
if (i < bytes.length - 1) {
sb.append(", ");
}
}
sb.append(" };").append("\r\n");
return sb.toString();
}

閱讀全文

與java實現udp相關的資料

熱點內容
二板股票源碼 瀏覽:440
度人經pdf 瀏覽:898
怎麼配置android遠程伺服器地址 瀏覽:956
java程序員看哪些書 瀏覽:939
什麼app可以免費和外國人聊天 瀏覽:793
pdf手寫筆 瀏覽:178
別永遠傷在童年pdf 瀏覽:986
愛上北斗星男友在哪個app上看 瀏覽:419
主力散戶派發源碼 瀏覽:669
linux如何修復伺服器時間 瀏覽:59
榮縣優途網約車app叫什麼 瀏覽:477
百姓網app截圖是什麼意思 瀏覽:226
php如何嵌入html 瀏覽:815
解壓專家怎麼傳輸 瀏覽:745
如何共享伺服器的網路連接 瀏覽:134
程序員簡易表白代碼 瀏覽:168
什麼是無線加密狗 瀏覽:64
國家反詐中心app為什麼會彈出 瀏覽:69
cad壓縮圖列印 瀏覽:104
網頁打開速度與伺服器有什麼關系 瀏覽:865