Java套接字编程头
我正在尝试通过 java 套接字发送文件并通过另一个套接字接收它。然而,这种情况发生了:
发送内容:
/* 这只是一个要传输的文件 */
已收到:
所以基本上我无法在堆栈溢出时转义收到的内容。它基本上是一堆不可读的字节(大约 32 个字节),然后是我发送的消息。
OutputStream os = sock.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(mybytearray);
oos.flush();
oos.close();
对于客户来说:
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
FileOutputStream fos = new FileOutputStream("newfile.java");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
sock.close();
I am trying to send a file through a java socket and receive it through another. However, this happens:
Send Content:
/*
This is simply a file to transfer
*/
Received:
so basically I cannot escape the received content on stack overflow. It is basically a bunch of unreadable bytes (about 32 bytes worth) and then the message I sent.
OutputStream os = sock.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(mybytearray);
oos.flush();
oos.close();
And for the client:
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
FileOutputStream fos = new FileOutputStream("newfile.java");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
sock.close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要通过
ObjectOutputStream
?可以直接通过write
方法使用OutputStream
,也可以选择例如DataOutputStream
(如果您认为有必要)。此外,您不应该使用
Reader
类来传输二进制数据。从Reader
的api:完整的“通过套接字发送文件”示例可以在这里找到:
通过套接字传输文件。
关键服务器端代码:
关键客户端代码:
Why go through
ObjectOutputStream
? Either use theOutputStream
directly through thewrite
method, or choose for instanceDataOutputStream
if you find it neccessary.Besides, you should not use the
Reader
classes for transferring binary data. From the api ofReader
:A complete "send file over socket" example can be found here:
Transfer a file via Socket.
Key server-side code:
Key client-side code:
查看代码会有所帮助,但你得到的看起来像是基本的随机数据。需要检查的一些事项:
It would help to see the code, but what you've got there looks like basic random data. Some things to check:
这没有任何意义。如果您使用 ObjectOutputStream,则必须使用 ObjectInputStream 来读取它。如果您想使用 Reader 来读取它,则必须使用 Writer 来写入它。
This doesn't make any sense. If you use an ObjectOutputStream you have to use an ObjectInputStream to read it. If you want to use a Reader to read it you have to use a Writer to write it.