本帖最后由 张然龙 于 2014-6-7 21:11 编辑
心血来潮想用UDP来传输图片,遇到几个不解的问:
1.我给接收端发了个结束标记over,为什么没退出循环来呢....
2.因为UDP传输不需要确认是否在线,所以我发图片怕丢包加了个一毫秒延时.图片完美的发送了过来 ,而且打开图片看了下,一点问题都没有.
但是发现大小竟然多了2994K.....为啥呢?
代码如下:↓
- class Fasong implements Runnable
- {
- public void run()
- {
- try
- {
- DatagramSocket ds=new DatagramSocket();
- byte []b=new byte[1024];
- InputStream is=new FileInputStream("D:\\截图.bmp");
- int len;
- while((len=is.read(b))!=-1)
- {
- DatagramPacket dp=new DatagramPacket(b,len,InetAddress.getByName("192.168.1.106"),50012);
- ds.send(dp);
- Thread.sleep(1);
- }
- b="over".getBytes();
- DatagramPacket dp=new DatagramPacket(b,"over".length(),InetAddress.getByName("192.168.1.106"),50012);
- ds.send(dp);
- ds.close();
- is.close();
- System.out.println("传输完毕!");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- class Jieshou implements Runnable
- {
- public void run()
- {
- try
- {
- DatagramSocket ds=new DatagramSocket(50012);
- byte []b=new byte [1024];
- OutputStream os=new FileOutputStream("D:\\截图备份.bmp");
- while(true)
- {
- DatagramPacket dp=new DatagramPacket(b,b.length);
- ds.receive(dp);
- if(new String(b).contains("over"))
- {
- break;
- }
- os.write(b);
- }
- System.out.println("接收完毕!");
- ds.close();
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public class Demo
- {
- public static void main(String[] args)throws Exception
- {
- new Thread(new Jieshou()).start();
- Thread.sleep(100);
- new Thread(new Fasong()).start();
- }
- }
复制代码
|