[英]Send String from server to client - save it as textfile
I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? 我知道如何将文件从服务器发送到客户端,但是如何将文本字符串发送到客户端,客户端将字符串另存为文件? Should I use
PrintWriter
for this issue? 我应该使用
PrintWriter
来解决此问题吗?
This is the code for sending a file from server to client: Sending files through sockets 这是用于从服务器向客户端发送文件的代码: 通过套接字发送文件
What I want to do is to (instead of sending a file), sending a String
from the server and let the client receive it and save it as a file. 我想做的是(而不是发送文件),从服务器发送一个
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();
}
}
in that case use ObjectOutputStream
at server side to write String and use ObjectInputStream
at client side to read String coming from server.. 在这种情况下,请在服务器端使用
ObjectOutputStream
编写String,并在客户端使用ObjectInputStream
读取来自服务器的String。
so your server() method will look like this.. 因此您的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();
}
and client() method will look like this.. 和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();
}
also throw ClassNotFoundException
in main method. 在主方法中也会抛出
ClassNotFoundException
。
public static void main(String[] args) throws IOException, ClassNotFoundException {.......}
done... 做...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.