各位高手,有知道怎么样使用WebSocket做推送的吗?能不能做一个简单,可以测试通的demo,并附加一定的说明,谢谢!
解决方案
40
import javax.websocket.ClientEndpoint; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; @ClientEndpoint public class Client{ @OnOpen public void onOpen(Session session){ } @OnClose public void onClose(Session session){ } @OnMessage public void onMessage(Session session,String message){ } @OnError public void onError(Session session,Throwable t){ } }
import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.pactera.caf.rtms.Courier; import com.pactera.caf.rtms.RTMessage; @ServerEndpoint("/rtms") public class Server{ @OnOpen public void onOpen(Session session){ } @OnClose public void onClose(Session session){ } @OnMessage public void onMessage(Session session,String message){ } @OnError public void onError(Session session,Throwable t){ } }
弄个Tomcat8,一定要8+,创建Dynamic Web Project。一定要使用Servlet3.1,然后工程里放Server.java即可,服务器就算部署完成了。客户端可以用HTML5的浏览器访问,也可以用Client.java适配。java的连接操作如下:
import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.Session; import javax.websocket.WebSocketContainer; ... WebSocketContainer container=ContainerProvider.getWebSocketContainer(); try{ URI uri=URI.create("ws://localhost:8080/rtms"); Client client=new Client(); Session session=container.connectToServer(client,uri); }catch(DeploymentException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }