Java中的WebSockets生产准备服务器?
编辑 :删除引用C#作为唯一的接受的答案是关于Java。 如果有人需要关于C#中websocket服务器实现的信息,请提出一个新问题。
你知道在Java中创buildWebSockets服务器的“生产就绪”框架吗? 我发现一个库http://nugget.codeplex.com/,但我不知道它是如何稳定和快速。
对于Java,看看这个内容丰富的post 。 从那里复制粘贴:
- Jetty WebSocket服务器 – 自去年9月以来,Jetty已经支持WebSocket。 这似乎是一个不错的select。
- Caucho树脂
- jWebSocket
- GlassFish / Grizzly (在这里看到一个DZone贴子)
- JBoss Netty (见这里的补丁)
- Webbit
在这些选项中,我猜Jetty和Resin是最成熟稳定的。 但是,总是很好地做你自己的testing。
接受的答案是3岁,随着最近发布的JEE7,现在每个实现servert 3.1的Web容器将通过标准API( javax.websocket )包支持websocket。
下面的代码展示了如何使用JEE7实现websocket的例子:
import java.util.logging.Level; import java.util.logging.Logger; 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; @ServerEndpoint(value = "/chat") public class ChatServer { private static final Logger LOGGER = Logger.getLogger(ChatServer.class.getName()); @OnOpen public void onOpen(Session session) { LOGGER.log(Level.INFO, "New connection with client: {0}", session.getId()); } @OnMessage public String onMessage(String message, Session session) { LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}", new Object[] {session.getId(), message}); return "Server received [" + message + "]"; } @OnClose public void onClose(Session session) { LOGGER.log(Level.INFO, "Close connection for client: {0}", session.getId()); } @OnError public void onError(Throwable exception, Session session) { LOGGER.log(Level.INFO, "Error for client: {0}", session.getId()); } }
在这里的例子详细。
支持Websocket的Web容器:
- 雄猫8
- WildFly (以前的Jboss AS)
- Glassfish 4.0
- 以及更多
Vert.x选项也值得考虑。
创build一个ws服务器可以很简单
vertx.websocketHandler(new Handler<ServerWebSocket>() { public void handle(ServerWebSocket ws) { // A WebSocket has connected! } }).listen(8080);
要么
vertx.createHttpServer().websocketHandler(new Handler<ServerWebSocket>() { @Override public void handle(final ServerWebSocket ws) { logger.info("ws connection established with " + ws.remoteAddress()); ws.dataHandler(new Handler<Buffer>() { @Override public void handle(Buffer data) { JsonObject item = new JsonObject(data.toString()); logger.info("data in -> " + item.encodePrettily()); // if you want to write something back in response to the client //ws.writeTextFrame(...); } }); } }).listen(port, new Handler<AsyncResult<HttpServer>>() { @Override public void handle(AsyncResult<HttpServer> event) { logger.info("ws server is up and listening on port " + port); } });
有关更多详细信息,请参阅http://vertx.io/docs/vertx-core/java/#_websockets
所以可以用Vert.x编写他自己的WebSocket服务器,把它打包成FatJar,然后自己运行。
或者你可以embeddedVert.x env。 在您的应用程序中,并以编程方式部署您的Verticle(实现ws服务器)。
另一种select是JBoss的Web服务器Undertow。 它很容易embedded到应用程序中。
添加这些依赖关系:
<dependency> <groupId>io.undertow</groupId> <artifactId>undertow-servlet</artifactId> <version>${version.io.undertow}</version> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-websockets-jsr</artifactId> <version>${version.io.undertow}</version> </dependency>
这里是一个示例ws服务器:
Undertow server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(path() .addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() { @Override public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) { channel.getReceiveSetter().set(new AbstractReceiveListener() { @Override protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { final String messageData = message.getData(); for (WebSocketChannel session : channel.getPeerConnections()) { WebSockets.sendText(messageData, session, null); } } }); channel.resumeReceives(); } })) .build(); server.start();
看看钢背骨架 。 这是一个常用的Java Websocket服务器,如Jetty,Netty或Tomcat的高级覆盖。 如果你喜欢Spring Framework,你一定要试试钢背兽!
免责声明:我是Bristleback Framework项目的贡献者。
Apache Tomcat 8.0实现了WebSockets 1.1 API( JSR-356 )。 你甚至可以通过导航到示例文件夹安装后玩例子:有回声聊天和蛇游戏。
docker
上个星期我花了很多时间来研究如何制作一个WebSocket服务器。 最后得到一些工作希望这有助于。 它使用来自Jetty(jar子)的库。
文件WebRTC_IceServer.java
package com.evanstools; import org.eclipse.jetty.server.*; import org.eclipse.jetty.websocket.server.*; public class WebRTC_IceServer{ public static void main(String[] args){ try{ //////////////////////// if(args.length == 0){ System.out.printf("%s%n","WebRTC_IceServer [port]"); return; } Server server = new Server(Integer.parseInt(args[0])); WebSocketHandler.Simple webSocketHandlerSimple = new WebSocketHandler.Simple(WebsocketPOJO.class); server.setHandler(webSocketHandlerSimple); server.start(); server.join(); //////////////////////// }catch(Exception w){w.printStackTrace();} } }
文件WebsocketPOJO.java
package com.evanstools; import org.eclipse.jetty.websocket.api.annotations.*; import org.eclipse.jetty.websocket.api.Session; //The class must be not abstract and public. @WebSocket public class WebsocketPOJO{ //Flags one method in the class as receiving the On Connect event. //Method must be public, not abstract, return void, and have a single Session parameter. @OnWebSocketConnect public void onWebSocketConnect(Session session){ System.out.printf("%s%n","test client connected"); } //Flags one method in the class as receiving the On Close event. //Method signature must be public, not abstract, and return void. //The method parameters: ////Session (optional) ////int closeCode (required) ////String closeReason (required) @OnWebSocketClose public void OnWebSocketClose(Session session,int closeCode,String closeReason){} //Flags up to 2 methods in the class as receiving On Message events. //You can have 1 method for TEXT messages, and 1 method for BINARY messages. //Method signature must be public, not abstract, and return void. //The method parameters for Text messages: ////Session (optional) ////String text (required) //The method parameters for Binary messages: ////Session (optional) ////byte buf[] (required) ////int offset (required) ////int length (required) @OnWebSocketMessage public void onWebSocketMessageString(Session session, String text){} //Flags one method in the class as receiving Error events from the WebSocket implementation. //Method signatures must be public, not abstract, and return void. //The method parameters: ////Session (optional) ////Throwable cause (required) //@OnWebSocketError //Flags one method in the class as receiving Frame events from the WebSocket implementation after they have been processed by any extensions declared during the Upgrade handshake. //Method signatures must be public, not abstract, and return void. //The method parameters: ////Session (optional) ///Frame (required) //The Frame received will be notified on this method, then be processed by Jetty, possibly resulting in another event, such as On Close, or On Message. Changes to the Frame will not be seen by Jetty. //@OnWebSocketFrame }