Java中的WebSocket生产就绪服务器?

Java中的WebSocket生产就绪服务器?,java,websocket,Java,Websocket,编辑:删除了对C的引用,因为唯一被接受的答案是关于Java的。如果有人需要关于C#中websocket服务器实现的信息,请提出新问题 您知道用Java创建WebSockets服务器的“生产就绪”框架吗?我找到了一个库,但我不知道它是如何稳定和快速的。对于Java,请查看此。从那里复制粘贴: –Jetty自去年9月以来一直支持WebSocket。这似乎是一个不错的选择 玻璃鱼/灰熊(见上面的DZone帖子) (请参阅修补程序) 在这些选项中,Jetty和Resin是最成熟和稳定的。但是,

编辑:删除了对C的引用,因为唯一被接受的答案是关于Java的。如果有人需要关于C#中websocket服务器实现的信息,请提出新问题

您知道用Java创建WebSockets服务器的“生产就绪”框架吗?我找到了一个库,但我不知道它是如何稳定和快速的。

对于Java,请查看此。从那里复制粘贴:

  • –Jetty自去年9月以来一直支持WebSocket。这似乎是一个不错的选择
  • 玻璃鱼/灰熊(见上面的DZone帖子)
  • (请参阅修补程序)
在这些选项中,JettyResin是最成熟和稳定的。但是,自己做测试总是很好的。

请看一下。它是常用JavaWebSocket服务器的高级覆盖,如Jetty、Netty或Tomcat。如果您喜欢Spring框架,您一定要尝试回刷


免责声明:我是刷毛回退框架项目的参与者。

公认的答案是3年前发布的JEE7,现在每个实现servert 3.1的Web容器都将通过标准API()包支持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容器:

  • (以前是JBossAS)
  • 还有更多

    • Vert.x选项也值得考虑

      创建ws-server可以非常简单

      vertx.websocketHandler(new Handler<ServerWebSocket>() {
          public void handle(ServerWebSocket ws) {
              // A WebSocket has connected!
          }
      }).listen(8080);
      
      实现WebSockets 1.1 API()。您甚至可以在安装后通过导航到examples文件夹来玩examples:有echo聊天和snake游戏

      码头

      过去一周我一直在琢磨如何制作WebSocket服务器。终于有办法了,希望能有所帮助。它使用来自Jetty(jars)的库

      文件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
      }
      

      嘿)好的)因为Jetty WebSockets(我可以相信它的实现),我接受了你的答案;)谢谢!;)当然,该项目是在LGPL.onbinary上托管的,并且是根据LGPL.onbinary获得许可的。API是否缺少部分?您指向Vert.x websockets文档的链接似乎已失效。这一个有效:@Pampy你是对的,我确认。更新了它。非常感谢你!
      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();
      
      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();}
      }
      }
      
      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
      }