我得到了java.lang.ClassCastException,但我正在发送对象,而不是字符串
我正在通过套接字发送序列化对象。问题是当我只发送一个字符串(消息)时,我在标题中提到了这个错误。下面是创建套接字对象的类:我得到了java.lang.ClassCastException,但我正在发送对象,而不是字符串,java,string,sockets,serialization,serversocket,Java,String,Sockets,Serialization,Serversocket,我正在通过套接字发送序列化对象。问题是当我只发送一个字符串(消息)时,我在标题中提到了这个错误。下面是创建套接字对象的类: package Pinger; import java.io.*; import java.util.Vector; public class ChatMessage implements Serializable { protected static final long serialVersionUID = 1112122200L; static final i
package Pinger;
import java.io.*;
import java.util.Vector;
public class ChatMessage implements Serializable {
protected static final long serialVersionUID = 1112122200L;
static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2, JOB = 3;
private int type,frequency,maxScans,NUMTHREADS,ttl;
Vector <String> IPS;
private String message;
// constructor
ChatMessage(int type, String message) {
this.type = type;
this.message = message;
}
ChatMessage (int type, int frequency, Vector <String> IPS, int maxScans, int NUMTHREADS, int ttl){
this.type=type;
this.frequency=frequency;
this.IPS=IPS;
this.maxScans=maxScans;
this.NUMTHREADS=NUMTHREADS;
this.ttl=ttl;
}
// getters
.
.
.
}
这里还有一个用于类客户端的GUI类:
package Pinger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
/*
* The Client with its GUI
*/
public class ClientGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
// will first hold "Username:", later on "Enter message"
private JLabel label;
// to hold the Username and later on the messages
private JTextField tf;
// to hold the server address an the port number
private JTextField tfServer, tfPort;
// to Logout and get the list of the users
private JButton login, logout, whoIsIn;
// for the chat room
private JTextArea ta;
// if it is for connection
private boolean connected;
// the Client object
private Client client;
// the default port number
private int defaultPort;
private String defaultHost;
InetAddress ComputerIP;
// Constructor connection receiving a socket number
ClientGUI(String host, int port) throws UnknownHostException {
super("Chat Client");
defaultPort = port;
defaultHost = host;
// The NorthPanel with:
JPanel northPanel = new JPanel(new GridLayout(3,1));
// the server name anmd the port number
JPanel serverAndPort = new JPanel(new GridLayout(1,5, 1, 3));
// the two JTextField with default value for server address and port number
tfServer = new JTextField(host);
tfPort = new JTextField("" + port);
tfPort.setHorizontalAlignment(SwingConstants.RIGHT);
serverAndPort.add(new JLabel("Server Address: "));
serverAndPort.add(tfServer);
serverAndPort.add(new JLabel("Port Number: "));
serverAndPort.add(tfPort);
serverAndPort.add(new JLabel(""));
// adds the Server an port field to the GUI
northPanel.add(serverAndPort);
// the Label and the TextField
ComputerIP = InetAddress.getLocalHost();
label = new JLabel("Enter your username below", SwingConstants.CENTER);
northPanel.add(label);
tf = new JTextField(ComputerIP.toString());
tf.setBackground(Color.WHITE);
northPanel.add(tf);
add(northPanel, BorderLayout.NORTH);
// The CenterPanel which is the chat room
ta = new JTextArea("Clients logs\n", 80, 80);
JPanel centerPanel = new JPanel(new GridLayout(1,1));
centerPanel.add(new JScrollPane(ta));
ta.setEditable(false);
add(centerPanel, BorderLayout.CENTER);
// the 3 buttons
login = new JButton("Login");
login.addActionListener(this);
logout = new JButton("Logout");
logout.addActionListener(this);
logout.setEnabled(false); // you have to login before being able to logout
whoIsIn = new JButton("Who is in");
whoIsIn.addActionListener(this);
whoIsIn.setEnabled(false); // you have to login before being able to Who is in
JPanel southPanel = new JPanel();
southPanel.add(login);
southPanel.add(logout);
southPanel.add(whoIsIn);
add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
tf.requestFocus();
}
// called by the Client to append text in the TextArea
void append(String str) {
ta.append(str);
ta.setCaretPosition(ta.getText().length() - 1);
}
// called by the GUI is the connection failed
// we reset our buttons, label, textfield
void connectionFailed() {
login.setEnabled(true);
logout.setEnabled(false);
whoIsIn.setEnabled(false);
InetAddress localIP = null;
label.setText("Enter your username below");
try {
localIP=InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tf.setText(localIP.getHostAddress().toString());
// reset port number and host name as a construction time
tfPort.setText("" + defaultPort);
tfServer.setText(defaultHost);
// let the user change them
tfServer.setEditable(false);
tfPort.setEditable(false);
// don't react to a <CR> after the username
tf.removeActionListener(this);
connected = false;
}
/*
* Button or JTextField clicked
*/
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
// if it is the Logout button
if(o == logout) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
return;
}
// if it the who is in button
if(o == whoIsIn) {
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
return;
}
// ok it is coming from the JTextField
if(connected) {
// just have to send the message
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText()));
tf.setText("");
return;
}
if(o == login) {
// ok it is a connection request
String username = tf.getText().trim();
// empty username ignore it
if(username.length() == 0)
return;
// empty serverAddress ignore it
String server = tfServer.getText().trim();
if(server.length() == 0)
return;
// empty or invalid port numer, ignore it
String portNumber = tfPort.getText().trim();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
return; // nothing I can do if port number is not valid
}
// try creating a new Client with GUI
client = new Client(server, port, username, this);
// test if we can start the Client
if(!client.start())
return;
tf.setText("");
label.setText("Enter your message below");
connected = true;
// disable login button
login.setEnabled(false);
// enable the 2 buttons
logout.setEnabled(true);
whoIsIn.setEnabled(true);
// disable the Server and Port JTextField
tfServer.setEditable(false);
tfPort.setEditable(false);
// Action listener for when the user enter a message
tf.addActionListener(this);
}
}
// to start the whole thing the server
public static void main(String[] args) throws UnknownHostException {
new ClientGUI("localhost", 6000);
}
}
那么这个呢:
sOutput.writeObject(username);
您发送到服务器的第一件事是一个
字符串
,在服务器端,您假设您正在获取一个聊天消息
很抱歉打扰了你们。问题是在服务器类,我并没有在这里显示(我的坏)。我通过套接字发送字符串而不是ChatMessage对象。这就是我出错的原因。我之前没有注意到。。。抱歉耽误了你的时间。问题出现在向所有客户端广播消息的服务器类中。ObjectInputStream被强制转换为字符串而不是ChatMessage()。再一次抱歉打扰你的。。。真糟糕…请发布异常StackTraceEded exception stacktrace。感谢您让我知道。因此您正在发送一个字符串
,并试图将其作为聊天信息
阅读。太本地化了。这是我唯一一次发送字符串。另外,当我提交消息时(也就是写并发送消息),我得到了错误。当客户端正在连接并且该部分工作正常时,会广播用户名。我会努力改变的。。。将告诉您我在代码中添加了程序发送SendMessage对象而不是字符串,但仍然出现相同的错误。如果需要分析和帮助,请不要发布摘要。“我在代码中添加了一个程序SendMessage对象,而不是字符串”并没有确切地告诉我们您做了什么;识别帖子中的行,并发布替换它的代码,或者类似的东西。
Exception in thread "Thread-2" java.lang.ClassCastException: java.lang.String cannot be
cast to Pinger.ChatMessage
at Pinger.Client$ListenFromServer.run(Client.java:143)
sOutput.writeObject(username);