传输Java对象,字节[]
问题描述:
你能来看看在这个?:传输Java对象,字节[]
这是我的客户:
try {
Socket socket = new Socket("127.0.0.1", 3000);
OutputStream out = socket.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(mp3data);
oos.close();
byte[] bytes = baos.toByteArray();
out.write(bytes);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我的服务器:
int port = 3000;
try {
ServerSocket clientConnect = new ServerSocket(port);
System.out.println("SimpleServer running on port" + port);
Socket clientSock = clientConnect.accept();
InputStream is = clientSock.getInputStream();
byte[] buffer = new byte[1024];
int read = is.read(buffer);
ObjectInputStream ois = new ObjectInputStream(is);
MP3[] songs = (MP3[])ois.readObject();
clientSock.close();
// HTML erzeugen
Website site = new Website("index2.html",songs);
} catch (Exception e) {
System.out.println (e);
}
它不工作。我没有得到任何例外,但网站构造函数没有被调用。
答
您假定整个字节数组只读取一次,并调用read()
,长度恰好为1024字节。事实并非如此(除非你非常幸运)。此外,您的ObjectInputStream正在封装已经读取构成消息的字节(或一些字节)的InputStream。而且,发件人写入的字节也不会被刷新。
不要忽略调用is.read()
的结果:它会告诉您实际上已读取了多少个字节。直到它不是-1,你应该继续阅读,在一个循环。
阅读关于byte streams的Java教程。
这就是说,你让事情变得困难。为什么不直接将对象写入套接字输出流,并直接从另一侧的套接字输入流中读取对象?
答
int port = 3000;
try {
ServerSocket clientConnect = new ServerSocket(port);
System.out.println("SimpleServer running on port" + port);
Socket clientSock = clientConnect.accept();
InputStream is = clientSock.getInputStream();
byte[] buffer = new byte[1024];
for (int i = 0; i < buffer.length; i++) {
int b = is.read();
if (b ==-1) break;
buffer[i] = (byte) b;
}
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer));
MP3[] songs = (MP3[])ois.readObject();;
ois.close();
clientSock.close();
您已经调试过吗? – burna
你应该在客户端的'out.write()'之后''out.flush()'。另外,在服务器端,您定义了一个尺寸仅为1024字节的缓冲区,我怀疑它能够接收到您希望接收的内容,除非我误认为... – fge
http://codereview.stackexchange.com/是更好的地方问这样的问题 –