簡體   English   中英

如何將從TCP / IP服務器收到的數據保存到Java中的文本文件中

[英]How to save data recieved from tcp/ip server into textfile in java

我用Java在Socket Network中編寫了一個小程序,該程序使用IP地址和端口號與服務器通信。 現在,來自服務器的數據將被連續接收。 我希望從服務器收到的所有這些數據都存儲在一個文本文件中,但是不知道如何在不掛起應用程序的情況下進行操作。

這是我的代碼:

public class Client
{

    public Client()
    {
        try
        {
            //ceating the socket to connect tso server running on same machine binded on port no 3000
            Socket client=new Socket("localhost",3000);
            System.out.println("Client connected ");
            //getting the o/p stream of that connection
            PrintStream out=new PrintStream(client.getOutputStream());
            //sending the message to server
            out.print("Hello from client\n");
            out.flush();
            //reading the response using input stream
            BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
            System.out.println(in.readLine());
            //closing the streams
            in.close();
            out.close();

        }
        catch(Exception err)
        {
            System.err.println("* err"+err);
        }

    }

    public static void main(String a[])
    {
        new Client();
    }
}   

提前致謝。

我有一個經過測試的代碼。嘗試這個。

  StringBuffer instr = new StringBuffer();

  /** Establish a socket connetion with the server*/
  Socket connection = new Socket(address, port);

  /** Instantiate a BufferedOutputStream object */
  BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());

  /** Instantiate an OutputStreamWriter object with the optional character
   * encoding. Sending some message to server
   */
  OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII"); 
  String process = "SAMPLE COMMAND SENT TO SERVER"+(char)13;

  /** Write across the socket connection and flush the buffer */
  osw.write(process);
  osw.flush();

  // NOW READING THE RESPONSE FROM THE SERVER
  // I HAVE ADDED THE CHAR(13) as the delimiter here
  /** Instantiate a BufferedInputStream object for reading
  /** Instantiate a BufferedInputStream object for reading
   * incoming socket streams.
   */

  BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
  /**Instantiate an InputStreamReader with the optional
   * character encoding.
   */

  InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

  /**Read the socket's InputStream and append to a StringBuffer */
  int c;
  while((c=isr.read())!=13)
    instr.append((char)c);

  /** Close the socket connection. */
  connection.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM