我正在为桌游制作超级简单的服务器。它获得了一个客户端连接,为我创建的Board Object创建了一个输入流,并将其发送回去。每当我在服务器或客户端中调用readObject时,都会收到java.lang.ClassNotFoundException错误。是什么原因造成的?
服务器插座
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(10000); //Don't timeout
}
public void run() {
while(true) {
try {
PlayerBoard board;
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(server.getInputStream());
//Get PlayerBoard Object from server.
board = (PlayerBoard)in.readObject(); //LINE THAT GIVES ME EXCEPTION
//Send PlayerBoard back
ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());
out.writeObject(board);
//Close server
server.close();
}catch(SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
}catch(IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) {
int port = 25565;
try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
客户插座
import apcslib.*;
import java.net.*;
import java.io.*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = "76.88.3.218";
PlayerBoard board;
int port = 25565;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(outToServer);
//Send server PlayerBoard object
out.writeObject(new PlayerBoard());
InputStream inFromServer = client.getInputStream();
ObjectInputStream in = new ObjectInputStream(inFromServer);
//Get PlayerBoard object back from server
board = (PlayerBoard)in.readObject(); //LINE THAT GIVES ME EXCEPTION
/*Loop to print out board to console
System.out.println("Board:");
System.out.print(" ");
for(int y = 1; y <= board.getWidth(); y++)
{
System.out.print(y + " ");
}
System.out.println();
for(int y = 0; y < board.getHeight(); y++)
{
System.out.print(Format.left(y+1, 3));
for (int x = 0; x < board.getWidth(); x++)
System.out.print(board.displaySpot(x, y) + " ");
System.out.println();
}*/
//Close connection
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
我收到的消息:
错误:(28,44)java:未报告的异常java.lang.ClassNotFoundException;必须被抓住或宣布被抛出
最佳答案
我对发生的事情有所了解,但是作为参考,您可以设置您的PlayerBoard
类吗?
有关我在想什么的参考:请参见 here 。
这是确保您能够正确读取对象的常规解决方案。如果服务器和客户端位于不同的项目中,则有两种方法可以达到正确的结果:
您必须具有两个相同的PlayerBoard
类(具有相同的包名称)。PlayerBoard
在提供给服务器和客户端项目的共享jar中。
对于您的演示(更有可能),如果您在同一项目中同时拥有Server和Client,则无需担心上述注意事项。
剩下的就是:PlayerBoard
必须实现Serializable
。如果您有两个PlayerBoard
类,则两个都必须以相同的方式实现Serializable
。