java中UDP文件传输怎么实现?

Python06

java中UDP文件传输怎么实现?,第1张

java UDP连接,如果要发送文件的话,你只能自己定义一系列的协议

因为TCP UDP 双方发送都是二进制数据

那么这个实现非常复杂

得不停的发送数据,写数据,建议使用http协议

//发送端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()

}

}