在看毕老师的UDP传输时,遇到点问题,,,就是在接收端怎么用循环来处理 ,,,,,求教了 ,,谢谢大
家,(就是说我在发送端要发送100M的数据,我在接受端肯定是预先不知道大小的,我怎么在接收端利用循环成功接收)
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- public class UDPSend {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- DatagramSocket ds=new DatagramSocket();
- //String str="UDP 演示";
- StringBuilder sb=new StringBuilder();
- InputStream is=new FileInputStream("a.txt");
- int a=-1;
- while((a=is.read())!=-1)
- {
- sb.append((char)a);
- }
- byte[] buf=sb.toString().getBytes();
- DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10000);
- ds.send(dp);
- ds.close();
-
- }
- }
- [code]import java.io.FileOutputStream;
- import java.io.OutputStream;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.SocketException;
- public class UDPReceiver {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- DatagramSocket ds=new DatagramSocket(10000);
- byte[] buf=new byte[1024];//如果我要给接受端传个100M的数据,我总不能new100M的数组吧,怎么用循环解决
- DatagramPacket dp=new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- //String ip=dp.getAddress().getHostAddress();
- //int prot=dp.getPort();
- String text=new String(dp.getData(),0,dp.getLength());
- //System.out.println(ip+prot+text);
- OutputStream os=new FileOutputStream("b.txt");
- os.write(text.getBytes());
-
- ds.close();
- }
- }
复制代码 [/code] |