簡體   English   中英

將字符串從服務器發送到客戶端-將其另存為文本文件

[英]Send String from server to client - save it as textfile

我知道如何將文件從服務器發送到客戶端,但是如何將文本字符串發送到客戶端,客戶端將字符串另存為文件? 我應該使用PrintWriter來解決此問題嗎?

這是用於從服務器向客戶端發送文件的代碼: 通過套接字發送文件

我想做的是(而不是發送文件),從服務器發送一個String ,並讓客戶端接收它並將其保存為文件。

public class SocketFileExample {
    static void server() throws IOException {
        ServerSocket ss = new ServerSocket(3434);
        Socket socket = ss.accept();
        InputStream in = new FileInputStream("send.jpg");
        OutputStream out = socket.getOutputStream();
        copy(in, out);
        out.close();
        in.close();
    }

    static void client() throws IOException {
        Socket socket = new Socket("localhost", 3434);
        InputStream in = socket.getInputStream();
        OutputStream out = new FileOutputStream("recv.jpg");
        copy(in, out);
        out.close();
        in.close();
    }

    static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread() {
            public void run() {
                try {
                    server();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        client();
    }
}

在這種情況下,請在服務器端使用ObjectOutputStream編寫String,並在客戶端使用ObjectInputStream讀取來自服務器的String。

因此您的server()方法將如下所示。

static void server() throws IOException {
    ServerSocket ss = new ServerSocket(3434);
    Socket socket = ss.accept();
    OutputStream out = socket.getOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(out);
    oout.writeObject("your string here");
    oout.close();
}

和client()方法將如下所示。

static void client() throws IOException, ClassNotFoundException {
    Socket socket = new Socket("localhost", 3434);
    InputStream in = socket.getInputStream();
    ObjectInputStream oin = new ObjectInputStream(in);
    String stringFromServer = (String) oin.readObject();
    FileWriter writer = new FileWriter("received.txt");
    writer.write(stringFromServer);
    in.close();
    writer.close();
}

在主方法中也會拋出ClassNotFoundException

public static void main(String[] args) throws IOException, ClassNotFoundException {.......}

做...

暫無
暫無

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

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