Java 中的 WebSockets 生产就绪服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4278456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WebSockets production ready server in Java?
提问by Edward83
EDIT: removed reference to C# as the only accepted answer is about Java. If someone needs information about websocket server implementation in C#, ask a new question.
编辑:删除了对 C# 的引用,因为唯一接受的答案是关于 Java。如果有人需要有关 C# 中 websocket 服务器实现的信息,请提出一个新问题。
Do you know "production ready" framework for creating WebSockets Server in Java? I found one library http://nugget.codeplex.com/but i did not know how it is stable and fast.
您知道在 Java 中创建 WebSockets Server 的“生产就绪”框架吗?我找到了一个库http://nugget.codeplex.com/但我不知道它是如何稳定和快速的。
采纳答案by Neeme Praks
For Java, check out this informative post. Copy-paste from there:
对于 Java,请查看这篇内容丰富的帖子。从那里复制粘贴:
- Jetty WebSocket Server– Jetty has supported WebSockets since last September. This seems to be a good option.
- Caucho Resin
- jWebSocket
- GlassFish/Grizzly(see a DZone posting on it here)
- JBoss Netty(see patch here)
- Webbit
- Jetty WebSocket 服务器——Jetty 自去年 9 月起就支持 WebSockets。这似乎是一个不错的选择。
- 高乔树脂
- jWebSocket
- GlassFish/Grizzly(在此处查看 DZone 上的帖子)
- JBoss Netty(请参阅此处的补丁)
- 网比特
Out of these options, I guess Jettyand Resinare the most mature and stable. However, always good to do your own testing.
在这些选项中,我猜Jetty和Resin是最成熟和最稳定的。但是,自己进行测试总是好的。
回答by voitec
Take a look at the Bristleback Framework. It is a high level overlay for commonly used Java Websocket Servers, like Jetty, Netty or Tomcat. If you like Spring Framework, you must definitely try Bristleback!
看看Bristleback 框架。它是常用 Java Websocket 服务器(如 Jetty、Netty 或 Tomcat)的高级覆盖。如果你喜欢 Spring Framework,你一定要试试 Bristleback!
Disclaimer: I'm a contributor in Bristleback Framework project.
免责声明:我是 Bristleback Framework 项目的贡献者。
回答by Pau Kiat Wee
The accepted answer is 3 years old, with the recent release of JEE7, now every Web Containers that implement servert 3.1 will support websocket via standard API (javax.websocket) package.
接受的答案是 3 年前,随着最近发布的 JEE7,现在每个实现 servert 3.1 的 Web 容器都将通过标准 API ( javax.websocket) 包支持 websocket 。
The following code show example how to implement websocket using JEE7:
以下代码显示了如何使用 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());
}
}
Example in details here.
此处详细示例。
Web Container that support Websocket:
支持 Websocket 的 Web 容器:
- Tomcat 8
- WildFly(Previously Jboss AS)
- Glassfish 4.0
- and much more
回答by aymens
The Vert.x option is also worth considering.
Vert.x 选项也值得考虑。
Creating a ws server can be as simple as
创建一个 ws 服务器可以很简单
vertx.websocketHandler(new Handler<ServerWebSocket>() {
public void handle(ServerWebSocket ws) {
// A WebSocket has connected!
}
}).listen(8080);
or
或者
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);
}
});
For more details look here http://vertx.io/docs/vertx-core/java/#_websockets
有关更多详细信息,请参见此处http://vertx.io/docs/vertx-core/java/#_websockets
So one can write his own WebSocket server with Vert.x, package it as FatJar, and run it on its own.
所以可以用 Vert.x 编写自己的 WebSocket 服务器,将其打包为 FatJar,并自行运行。
Or you can embed Vert.x env. in your app, and deploy your verticle (that implements the ws server) programmatically.
或者您可以嵌入 Vert.x 环境。在您的应用程序中,并以编程方式部署您的 Verticle(实现 ws 服务器)。
Another alternative is JBoss's web server Undertow. Which is easily embeddable in applications.
另一种选择是 JBoss 的 Web 服务器 Undertow。这很容易嵌入到应用程序中。
Add these dependencies:
添加这些依赖项:
<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>
And here's a sample ws server:
这是一个示例 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();
回答by timeking
Apache Tomcat 8.0implements WebSockets 1.1 API (JSR-356). You can even play with examples after installing by navigating to examples folder: there are echo chat and snake game.
Apache Tomcat 8.0实现了 WebSockets 1.1 API ( JSR-356)。您甚至可以在安装后通过导航到示例文件夹来玩示例:有回声聊天和蛇游戏。
回答by user28775
JETTY
码头
I've spent the past week mauling over how to make a WebSocket server. Finally got something to work hope this helps. It uses libraries from Jetty (jars).
过去一周我一直在研究如何制作 WebSocket 服务器。终于得到了一些工作希望这会有所帮助。它使用来自 Jetty (jars) 的库。
File WebRTC_IceServer.java
文件 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();}
}
}
File WebsocketPOJO.java
文件 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
}