我有一台服务器,这为很多客户服务。所有客户端都连接到服务器。服务器在不同的线程上为每个客户端提供服务,该线程将对象发送到客户端。这些线程中的每一个都使用方法returnToken()
,因为它返回在主类中创建的标记实例。问题是,客户端接收对象(或似乎),但无法访问其属性。当客户端访问对象的属性时,返回null
。除此之外,不使用entrada
类中的对象标记。
public class ThreadServidor extends Thread implements Runnable{
Socket cliente;
ThreadServidor(Socket cliente){
this.cliente = cliente;
}
@Override
public void run() {
ObjectOutputStream saida = null;
try {
saida = new ObjectOutputStream(cliente.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(ThreadServidor.class.getName()).log(Level.SEVERE, null, ex);
}
while(true){
try {
saida.writeUnshared(Token.returnToken());
saida.flush();
saida.reset();
} catch (IOException ex) {
Logger.getLogger(ThreadServidor.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(15000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadServidor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
我的班级entrada在客户端:
public class Entrada implements Runnable {
private Socket servidor;
private String id;
Entrada(Socket cliente, String id){
this.servidor = cliente;
this.id = id;
}
@Override
public void run() {
ObjectInputStream entrada = null;
try {
entrada = new ObjectInputStream(servidor.getInputStream());
} catch (IOException ex) {
Logger.getLogger(Entrada.class.getName()).log(Level.SEVERE, null, ex);
}
// Loop principal
while (true) {
try {
try {
// Recebe mensagem do servidor
Token token = (Token) entrada.readUnshared();
System.out.println("Sender is "+Token.returnSender());
} catch (IOException ex) {
Logger.getLogger(Entrada.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Entrada.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
令牌类:
public class Token implements Serializable {
private static final long serialVersionUID = 1L;
public static String sender, receiver, content;
String id;
public Token(String sender, String receiver, String content){
Token.sender = sender;
Token.receiver = receiver;
Token.content = content;
}
public static Token returnToken(){
Token token = new Token(Token.sender, Token.receiver, Token.content);
return token;
}
public static String returnSender(){
System.out.println("Sender is "+sender);
return Token.sender;
}
public boolean hasToken(String id){
if(Token.sender.equals(id)){
return true;
}
else {return false;}
}
}
答案 0 :(得分:1)
静态字段未序列化。让他们成为实例成员。
您需要单独捕捉EOFException
并在捕获时停止阅读。