2010-11-25 5 views
24

EDIT : Java에 관한 유일한 대답이 C#에 대한 참조를 제거했습니다. C#에서 websocket 서버 구현에 대한 정보가 필요한 경우 새로운 질문을하십시오.WebSocket 프로덕션 준비 서버 Java?

Java에서 WebSockets Server를 만들기위한 "프로덕션 준비"프레임 워크를 알고 있습니까? 하나의 라이브러리를 찾았습니다. http://nugget.codeplex.com/하지만 안정적이고 빠릅니다.

답변

35

자바의 경우이 informative post을 확인하십시오. 거기에서 복사 - 붙여 넣기 :

이러한 옵션 중, 나는 부두수지 가장 성숙하고 안정 같아요. 그러나, 항상 자신의 테스트를 수행하는 것이 좋습니다.

+0

ㅎ) 확인) (내가 대답을 받아이) 실현의 믿을 수있는, 감사)!;) – Edward83

2

Bristleback Framework을 살펴보십시오. Jetty, Netty 또는 Tomcat과 같이 일반적으로 사용되는 Java Websocket Server의 상위 수준 오버레이입니다. Spring Framework가 마음에 드시면 Bristleback을 꼭 사용해보십시오!

면책 조항 : 나는 Bristleback Framework 프로젝트의 제공자입니다.

+0

voitec, 무료입니까? – Edward83

+0

물론 프로젝트는 [GitHub] (https://github.com/bristleback/bristleback)에서 호스팅되며 LGPL에서 라이센스가 부여됩니다. – voitec

+0

아주 좋은, 일 계속! – Edward83

45

승인 된 답변은 최근 3 개월이며, JEE7의 최신 릴리스에서는 이제 servert 3.1을 구현하는 모든 웹 컨테이너가 표준 API (javax.websocket) 패키지를 통해 websocket을 지원합니다.

JEE7를 사용하여 웹 소켓을 구현하는 방법을 다음 코드 쇼 예 : 자세한 내용은 here에서

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()); 
    } 
} 

예.

는 웹 소켓 지원

웹 컨테이너 :

+0

onbinary가 없거나 API의 일부가 아닙니다. –

4

Vert.x 옵션도 가치가있다 치고는.

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); 
     } 
    }); 

그래서 하나가 Vert.x와 자신의 웹 소켓 서버를 쓸 수 있습니다 여기에 http://vertx.io/docs/vertx-core/java/#_websockets

을 보면 간단 같은 WS 서버를 생성 할 수있다 , 그것을 FatJar로 패키지화하고, 그것을 독자적으로 실행하십시오.

또는 Vert.x env를 포함 할 수 있습니다. 귀하의 응용 프로그램에서, 그리고 verticle (ws 서버를 구현) 프로그래밍 방식으로 배포 할 수 있습니다.


또 다른 대안은 JBoss의 웹 서버 언더우드입니다. 어떤 응용 프로그램에 쉽게 포함 할 수 있습니다. 샘플 WS 서버의 여기

<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> 

을 그리고 :

이러한 종속성을 추가

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(); 
+0

Vert.x 웹 소켓 문서에 대한 링크가 작동하지 않는 것 같습니다. 이 작품은 다음과 같습니다 : http://vertx.io/docs/vertx-core/java/#_websockets – Pampy

+0

@Pampy 맞습니다. 그것을 업데이트했습니다. 정말 고맙습니다! – aymens

0

Apache Tomcat 8.0는 WebSocket을 1.1 API (JSR-356)를 구현합니다. 예제 폴더로 이동하여 설치 한 후에도 예제로 재생할 수 있습니다 : 에코 채팅 및 뱀 게임이 있습니다.

0

부두

나는 웹 소켓 서버를 만드는 방법을 통해 지난 주 mauling을 보냈어요. 마침내 뭔가 도움이 되었으면 좋겠다. 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();} 
} 
} 

때문에 부두 WebSocket을의 파일 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 
} 
관련 문제