简体   繁体   English

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

[英]Couldn't write in a file when receiving the data via socket connection in java

I tried to implement a send-receive example via a socket but It didn't work well. 我试图通过套接字实现一个收发示例,但效果不佳。 The sender sends the data successfully and the Receiver receives the data and shown in the console but I want to save this data in a file and I couldn't. 发送方成功发送数据,接收方接收到数据并显示在控制台中,但是我想将此数据保存在文件中,但我不能。 As I noticed that the receiver keeps listeninig without ending the while loop. 正如我注意到的那样,接收方保留了listeninig而不结束while循环。 So can anyone help me to solve this problem ? 那么有人可以帮助我解决这个问题吗?

The Sender module 发件人模块

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 

 }

The Receiver module 接收器模块

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);
        }

    }
}

Thanks in advance. 提前致谢。

You can achive it by following code changes.In Receiver class make changes in following loop. 您可以通过以下代码更改来实现它。在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);
                 */
            }

EDIT 编辑

Complete Code of the Program which is running successfully. 成功运行的程序的完整代码。

Sender 发件人

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 

 }

Receiver 接收者

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);
        }

    }
}

Look at your receiver loop: 查看您的接收器循环:

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()));
}

Leaving aside the various character encoding issues etc, how would you ever expect receiveData to become null in that loop? 撇开各种字符编码问题等等,你会怎么指望 receiveData成为null在这个循环? How could the loop end? 循环怎么结束?

Given that you're using UDP instead of TCP, you don't really have a connection, so how are you expecting to tell when the writer has stopped writing? 假设您使用的是UDP而不是TCP,那么您实际上并没有连接,那么如何期望知道编写者何时停止编写? Additionally, you should the consider the possibility of packets arriving out of order. 另外,您应该考虑数据包乱序到达的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM