我正在尝试读取一个使用Socket程序从客户端发送的字符串,代码如下:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 5000;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
但是从客户端读取字符串时,我收到如下错误:
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 54657374
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:803)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at SocketServerExample.main(SocketServerExample.java:29)
我搜索了但没有管理找到错误。请帮帮我。
答案 0 :(得分:28)
显然,您没有使用ObjectOutputStream:
发送数据,而只是在写字节。
readObject()
阅读,则必须使用writeObject().
readUTF()
阅读,则必须使用writeUTF().
readXXX()
阅读,则必须使用writeXXX(),
为大多数XXX值撰写。答案 1 :(得分:5)
您不能指望ObjectInputStream
自动将文本转换为对象。十六进制54657374
为"Test"
为文本。您必须直接以字节发送它。