我是java客户端服务器通信的新手,我遇到了从客户端向服务器端发送对象的问题。不知何故,我的程序在尝试传输对象时卡住了。可能的原因可能是ObjectOutputStream实现。
数据库登录按钮
class Handler implements ActionListener {
Client client = new Client();
List<String> parameterList = new ArrayList<String>();
ClientParameter parameter;
public void actionPerformed(ActionEvent event) {
if(event.getSource()==buttonConnect) {
parameterList.add(username);
parameterList.add(password);
parameter = new ClientParameter(parameterList);
client.connectToServer(parameter);
}
Object ClientParameter
public class ClientParameter {
List<String> parameterList;
public ClientParameter(List<String> parameterList) {
this.parameterList = parameterList;
}
public List<String> getParameterList() {
return parameterList;
}
public void setParameterList(List<String> parameterList) {
this.parameterList = parameterList;
}
}
班级客户
public void connectToServer(ClientParameter parameter) {
// Verbindung mit dem Server herstellen
Socket server = null;
try {
server = new Socket("localhost", 3141);
// programm hangs while reading this 2 lines..
ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());
ObjectOutputStream objectOut = new ObjectOutputStream(server.getOutputStream());
objectOut.writeObject(parameter);
} catch(UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if(server!=null) {
try {
server.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
}
服务器类
public class Server {
private static void handleConnection(Socket client) throws IOException {
ObjectInputStream objectIn = new ObjectInputStream(client.getInputStream());
ObjectOutputStream objectOut = new ObjectOutputStream(client.getOutputStream());
ClientParameter parameter;
try {
parameter = (ClientParameter) objectIn.readObject();
System.out.println(parameter);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(3141);
while(true) {
Socket client = null;
try {
client = server.accept();
handleConnection(client);
}
catch(IOException e) {
e.printStackTrace();
}
finally {
if(client!=null) {
try {
client.close();
}
catch(IOException e) {
System.out.println(e);
}
}
}
}
}
}
谢谢!
答案 0 :(得分:3)
服务器首先读取客户端发送的内容。客户端也从读取服务器发送的内容开始。所以这是一个僵局。
确实,as documented,ObjectInputStream的构造函数阻塞,直到它收到序列化流头:
从流中读取序列化流标头并进行验证。此构造函数将阻塞,直到相应的ObjectOutputStream已写入并刷新标头。
删除以下行,因为您无论如何都不对ObjectInputStream执行任何操作:
ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());