SimpleClient.java類未發現異常
import java.net.*;
import java.io.*;
class testobject implements Serializable {
int value;
String id;
public testobject(int v, String s) {
this.value = v;
this.id = s;
}
}
public class SimpleClient {
public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 2002);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
testobject to = new testobject(1, "object from client");
oos.writeObject(to);
oos.writeObject(new String("another object from the client"));
oos.close();
os.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
SimpleServer.java
import java.net.*;
import java.io.*;
class testobject implements Serializable {
int value;
String id;
public testobject(int v, String s) {
this.value = v;
this.id = s;
}
}
public class SimpleServer {
public static void main(String args[]) {
int port = 2002;
try {
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
testobject to = (testobject) ois.readObject();
if (to != null) {
System.out.println(to.id);
}
System.out.println((String) ois.readObject());
is.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
了兩個類**一模一樣的**包?既然你還沒有宣佈[的serialVersionUID(https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it),一舉兩得類**準確相同的**內容?更重要的是;爲什麼不將'TestObject'作爲一個單獨的單元編譯並在其他項目中使用?最後Java中的類在** PascalCase中總是**,**沒有藉口**。 –
你應該做一個JAR文件爲您的「芯」的對象,並使用它作爲你的兩個項目之間的庫。不要讓「看起來」相同的兩個獨立的Java類 –