你会看看这个吗?:
这是我的客户:
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);
}
这不行。我没有任何例外,但没有调用Website-Constructor。
答案 0 :(得分:1)
您假设只在一次调用read()
时读取整个字节数组,并且其长度恰好为1024字节。事实并非如此(除非你非常幸运)。此外,您的ObjectInputStream正在包装InputStream,您已经从中读取了构成消息的字节(或一些字节)。而且,发送者写入的字节不会被刷新。
不要忽略对is.read()
的调用结果:它告诉你实际读取了多少字节。直到它不是-1,你应该继续循环阅读。
阅读byte streams上的Java教程。
那就是说,你让事情变得困难。为什么不直接将对象写入套接字输出流,并直接从另一端的套接字输入流中读取对象?
答案 1 :(得分:0)
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();