所以我只是在测试一些客户端-服务器的东西(我在一个更大的项目中处理它,但它一直在抛出错误,所以我决定确保我做对了。结果我不是)这涉及 ObjectOutput和输入流。当我在 localhost 上运行客户端和服务器时,它可以完美运行,但是如果我在我的 linux 服务器上运行服务器并在我的计算机上运行客户端,那么当我到达获取对象的行时,连接已经重置。这是代码:
客户:
public static void main(String[] args){
String[] stuff = {"test", "testing", "tester"};
Socket s = null;
ObjectOutputStream oos = null;
try {
s = new Socket("my.server.website", 60232);
oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(stuff);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
s.close();
oos.close();
} catch (IOException e) {}
}
}
服务器:
public static void main(String[] args){
ServerSocket ss = null;
Socket s = null;
ObjectInputStream ois = null;
try {
ss = new ServerSocket(60232);
s = ss.accept();
System.out.println("Socket Accepted");
ois = new ObjectInputStream(s.getInputStream());
Object object = ois.readObject();
System.out.println("Object received");
if (object instanceof String[]){
String[] components = (String[]) object;
for (String string : components){
System.out.println(string);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
ss.close();
s.close();
ois.close();
} catch (IOException e) {}
}
}