在java中通过套接字连接接收数据时无法写入文件

时间:2012-05-13 10:43:41

标签: java sockets datagram

我尝试通过套接字实现发送 - 接收示例,但它没有成功。发送方成功发送数据,接收方接收数据并显示在控制台中,但我想将这些数据保存在文件中,我无法做到。当我注意到接收器保持listeninig而不结束while循环。那么有人可以帮我解决这个问题吗?

发件人模块

import java.io.*;
import java.net.*; 
import java.util.*;


public class UDPSend {


 public static void main(String[] args) throws IOException
  {
      FileInputStream fstream = new FileInputStream("T.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      File file = new File("T.txt");
      FileInputStream fis = new FileInputStream(file);
      byte[] fsize = new byte[(int) file.length()];
      int size = fis.read(fsize);
                System.out.println("Size = " + size);



      InetAddress addr = InetAddress.getByName("localhost");
      byte[]  buf  = new byte[10000];

      String DataLine; 
      while ((DataLine = br.readLine()) != null)  
      { 
                DatagramPacket packet =new DatagramPacket(DataLine.getBytes(),         DataLine.length() , addr, 4555);
          System.out.println (DataLine);
          DatagramSocket socket = new DatagramSocket();
          socket.send(packet);

      }//end while loop


  }//end main method 

 }

接收器模块

import java.io.*;
import java.net.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class UDPRecieve {



public static void main(String args[]) throws Exception
      {

      FileWriter fw = new FileWriter(new File("D:/JavaPrograms/Multimedia-proj-2/src/outtt.txt"));
      fw.write("hi");
      try{
      //DatagramSocket serverSocket = new DatagramSocket(4555);
      DatagramSocket Socket = new DatagramSocket(4555);
      byte[] receiveData = new byte[1000000];    
     // byte[] sendData = new byte[1024];
      //while(true)
      while(receiveData !=null)
         {  
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            Socket.receive(receivePacket);
            String sentence = new String( receivePacket.getData());
            fw.write(sentence);
            fw.flush();
            System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
            //System.out.println("Done");
            //InetAddress IPAddress = receivePacket.getAddress();
            //int port = receivePacket.getPort();
            //String capitalizedSentence = sentence.toUpperCase();
           /* sendData = capitalizedSentence.getBytes();
            DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, port);
            serverSocket.send(sendPacket);*/
         }


      fw.flush();
      fw.close(); 

      } catch (Exception e) {
          System.err.println(e);
        }

    }
}

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以通过以下代码更改来实现它。在Receiver类中,在以下循环中进行更改。

while (receiveData != null) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData,
                        receiveData.length);
                Socket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());
                fw.write(sentence.trim());
                fw.flush();
                System.out.printf("RECEIVED: %s ", new String(receivePacket
                        .getData()));
                // System.out.println("Done");
                // InetAddress IPAddress = receivePacket.getAddress();
                // int port = receivePacket.getPort();
                // String capitalizedSentence = sentence.toUpperCase();
                /*
                 * sendData = capitalizedSentence.getBytes(); DatagramPacket
                 * sendPacket = new DatagramPacket(sendData, sendData.length,
                 * IPAddress, port); serverSocket.send(sendPacket);
                 */
            }

修改

已成功运行的完整程序代码。

<强>发件人

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UDPSend {


 public static void main(String[] args) throws IOException
  {
      FileInputStream fstream = new FileInputStream("D:/T.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      File file = new File("D:/T.txt");
      FileInputStream fis = new FileInputStream(file);
      byte[] fsize = new byte[(int) file.length()];
      int size = fis.read(fsize);
                System.out.println("Size = " + size);



      InetAddress addr = InetAddress.getByName("localhost");
      byte[]  buf  = new byte[10000];

      String DataLine; 
      while ((DataLine = br.readLine()) != null)  
      { 
                DatagramPacket packet =new DatagramPacket(DataLine.getBytes(),         DataLine.length() , addr, 4555);
          System.out.println (DataLine);
          DatagramSocket socket = new DatagramSocket();
          socket.send(packet);

      }//end while loop


  }//end main method 

 }

<强>接收机

import java.io.File;
import java.io.FileWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {

    public static void main(String args[]) throws Exception {

        FileWriter fw = new FileWriter(new File(
                "D:/outtt.txt"));
        fw.write("hi");
        try {
            // DatagramSocket serverSocket = new DatagramSocket(4555);
            DatagramSocket Socket = new DatagramSocket(4555);
            byte[] receiveData = new byte[1000000];
            // byte[] sendData = new byte[1024];
            // while(true)
            while (receiveData != null) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData,
                        receiveData.length);
                Socket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());
                fw.write(sentence.trim());
                fw.flush();
                System.out.printf("RECEIVED: %s ", new String(receivePacket
                        .getData()));
                // System.out.println("Done");
                // InetAddress IPAddress = receivePacket.getAddress();
                // int port = receivePacket.getPort();
                // String capitalizedSentence = sentence.toUpperCase();
                /*
                 * sendData = capitalizedSentence.getBytes(); DatagramPacket
                 * sendPacket = new DatagramPacket(sendData, sendData.length,
                 * IPAddress, port); serverSocket.send(sendPacket);
                 */
            }

            fw.flush();
            fw.close();

        } catch (Exception e) {
            System.err.println(e);
        }

    }
}

答案 1 :(得分:0)

看看你的接收器循环:

while(receiveData != null)
{  
     DatagramPacket receivePacket = new DatagramPacket(receiveData,
                                                       receiveData.length);
     Socket.receive(receivePacket);
     String sentence = new String( receivePacket.getData());
     fw.write(sentence);
     fw.flush();
     System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
}

不考虑各种字符编码问题等,您将希望{/ 1>}在该循环中成为receiveData如何循环结束?

鉴于您使用的是UDP而不是TCP,您实际上没有连接,那么您希望在作者停止写作时如何判断?此外,您应该考虑数据包无法到达的可能性。