自己写了一段代码,实现的功能是,从发送端指定一个文件,在接收端实现控制台输出,为什么每次输出的结果都不完整,请高手解释。
发送端代码:- class UDPDemo {
- public static void main(String [] agre)throws Exception{
- while(true){
- System.out.println("请输入你要发送的文件地址");
- BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
- String uil=bf.readLine();
- FileInputStream fiin=new FileInputStream(uil);
- byte []fiby=new byte[1024];
- int len=-1;
- DatagramSocket ds=new DatagramSocket();
- while((len=fiin.read(fiby))!=-1){
- System.out.println(len);
- DatagramPacket dp =new DatagramPacket(fiby,1024,InetAddress.getByName("192.168.0.101"),1055);
- ds.send(dp);
- }}
- }
- }
复制代码 接收端代码:- class UdpReceive
- {
- public static void main(String[] args) throws SocketException
- {
- DatagramPacket packet = null;
- DatagramSocket socket = null;
- byte[] recvBuf = new byte[1024];
- int port = 1055;
- socket = new DatagramSocket(port);
- System.out.println("WATING FOR MSG...");
- while(true){
- packet = new DatagramPacket(recvBuf, recvBuf.length);
- while (packet.getData().length != 0)
- {
- try
- {
- socket.receive(packet);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- String recvstr = new String(recvBuf, 0, packet.getLength());
- String sourceIp = packet.getAddress().getHostAddress();
- System.out.println("从设备: " + sourceIp + " 接受到原始报文: " + recvstr);
- }
- } }
- }
复制代码
|
|