对于我正在学习的 Java 类,我需要使用套接字在客户端和服务器之间来回传递数据。虽然我可以获得传递字符串数据的示例,但我需要能够来回传递自定义类对象(即产品)和这些对象的列表。我无法让服务器成功读取输入。我尝试创建一个简单的代码示例,看看是否有人可以查明问题所在。我确实知道我没有完整的代码,但我什至无法让服务器读取该类正在写入流的对象(在这种情况下,我正在编写一个字符串只是为了尝试让它工作,但需要读/写对象)。这是我的代码。我花了好几个小时尝试这个并研究其他人的问题和答案,但仍然无法让它发挥作用。
这里是示例代码:
简单的服务器:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class simpleServer {
public static final int PORT_NO = 8888;
static ObjectInputStream serverReader = null;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket = new ServerSocket(PORT_NO);
System.out.println("... server is accepting request");
Object myObject = null;
while (true) {
Socket socket = serverSocket.accept();
System.out.println("creating reader");
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
serverReader = new ObjectInputStream(socket.getInputStream());
System.out.println("created reader");
try {
System.out.println("try to read");
myObject = serverReader.readObject();
System.out.println("read it");
System.out.println(myObject);
if (myObject != null) objOut.writeUTF("Got something");
else objOut.writeUTF("got nothing");
if ("quit".equals(myObject.toString())) serverSocket.close();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("cath for readobject");
}
catch (Exception e) {
System.out.println("other error");
System.out.println(e.getMessage());
}
}
}
}
简单的客户端:
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket("localhost", ProductDBServer.PORT_NO);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeUTF("loadProductsFromDisk");
objOut.flush();
String myString = objIn.toString();
//System.out.println(myString);
if (!"quit".equals(objIn.toString().trim())) {
//System.out.println("reading line 1");
String line;
try {
line = (String)objIn.readObject();
//System.out.println("line is " + line);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
objIn.close();
//System.out.println("result: " + line);
}
System.out.println("closing socket");
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("Unknownhostexception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("ioexception");
e.printStackTrace();
}
}
代码似乎运行到服务器端尝试读取我发送的对象的位置,然后死掉。有人可以看到我做错了什么吗?这似乎是一件很简单的事情,但我似乎无法让它发挥作用。谢谢你的帮助!