2014-10-31 103 views
1

我創建了一個@ServerEndpointDecodersEncoders參數類型不匹配@onmessage

服務器獲取我的錯誤:java.lang.IllegalArgumentException: argument type mismatch當我用session.sendObject(message)服務器

我瞪大眼睛而有所不同,但無法找到問題的發送對象。 這是我serverEndpoint

@ServerEndpoint(value="/room" 
     , encoders = MessageEncoder.class 
     , decoders = MessageDecoder.class) 
public class myServerEndpoint 
{ 
    @OnMessage 
    public void onMessage(Message message, Session session) 
    { 
     //some code to proccess message 
    } 
} 

,這是我MessageDecoder:

public class MessageDecoder implements Decoder.Text<Message> 
{ 
    public Message decode(String str) throws DecodeException 
    { 
     JsonObject obj = Json 
       .createReader(new StringReader(str)).readObject(); 

     Message msg = new Message(); 
     msg.setMessage(obj.getString("message")); 
     msg.setSender(obj.getString("sender")); 
     msg.setReceivedDate((Date) obj.get("receivedDate")); 

     return msg; 
    } 
    //... and other Methods 
} 

,這是我Message.class

public class Message implements Serializable 
{ 
    private String message; 
    private String sender; 
    private Date receivedDate; 

    public Message() {} 
    //setters and getters 
} 

,這是我的客戶端代碼:

public static void main(String[] args) 
{ 
    WebSocketContainer container = ContainerProvider.getWebSocketContainer(); 
    Session session = container 
      .connectToServer(WSClient.class, 
      URI.create("ws://localhost:8080/mySocket/room")); 

    Message msg = new Message(); 
    msg.setMessage("msg"); 
    msg.setSender("me"); 
    msg.setReceivedDate(new Date()); 

    session.getBasicRemote().sendObject(msg); 
} 

當我嘗試將對象發送到服務器和服務器時發生問題,例如java.lang.IllegalArgumentException: argument type mismatch

什麼是問題?

回答

0

我終於找到我的問題了。

MessageTextDecodewillDecode功能是返回falseserverEndpoint是說argument type mismatch

如果字符串沒有問題,函數應返回true

public boolean willDecode(String arg0) 
{ 
    return true; // in previous my code this returned false 
}