Я ищу решение для моей ошибки, возникающей при попытке отправить объект со стороны сервера на клиентскую.отправка объектов на/из клиента/сервера
Объект в форме как экземпляр класса будет создан путем нажатия на JButton. Также будет создан клиентский класс, который переносит объект на сервер. Ошибок не будет. Но когда дело доходит до отправки нового объекта обратно клиенту, будет выбрано ClassCastException.
ActionListener Класс
class ActionHandler implements ActionListener {
String buttonPressed;
List<String> parameterList = new ArrayList<String>();
public void actionPerformed(ActionEvent event) {
if(event.getSource() == executeNameSearch) {
buttonPressed = "NameSearch";
parameterList = new ArrayList<String>();
parameterList.add(pizzaNameSearch.getText());
ObjectToServer object = new ObjectToServer(buttonPressed, parameterList);
// build connection to server
Client client = new Client();
client.connectToServer(object);
}
else if(event.getSource() == executeNameSearch) {
buttonPressed = "IDSuche";
parameterList = new ArrayList<String>();
parameterList.add(pizzaIDSearch.getText());
ObjectToServer object = new ObjectToServer(buttonPressed, parameterList);
Client client = new Client();
client.connectToServer(object);
}
// some more actionPerformed cases..
}
}
класс Client
public class Client {
public void connectToServer(ObjectToServer object) {
Socket server = null;
try {
server = new Socket("localhost", 3141);
ObjectOutputStream oos = new ObjectOutputStream(server.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(server.getInputStream());
// sending object to server
oos.writeObject(object);
oos.flush();
// receiving object from server
try {
// ERROR BY TRYING TO CAST HERE
ObjectToClient objectIn = (ObjectToClient) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
oos.close();
ois.close();
} catch(UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if(server!=null) {
try {
server.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
}
}
Class Server
public class Server {
static PizzaManager manager = new PizzaManager();
private static void handleConnection(Socket client) throws IOException {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectToServer objectIn;
try {
objectIn = (ObjectToServer) ois.readObject();
String buttonPressed = objectIn.getButtonPressed();
if(buttonPressed.equals("NamenSuche")) {
String searchedPizzaName = objectIn.getParameterList().get(0);
manager.namenSuche(searchedPizzaName);
ObjectToClient objectOut = new ObjectToClient();
objectOut.setResults(manager.getResults());
oos.writeObject(objectIn);
}
// some more cases..
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
oos.close();
}
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) {
}
}
}
}
}
}
StackTrace
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
transfer.ObjectToServer cannot be cast to server.ObjectToClient
at client.Client.connectToServer(Client.java:34)
at gui.Pizzasuche$ActionHandler.actionPerformed(Pizzasuche.java:362)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Спасибо за вашу помощь!
Очевидно, что объект ожидается не объект на самом деле послал. У вас где-то есть логическая ошибка. Вы неправильно используете свой собственный протокол приложения. – EJP