从java应用程序连接到webSocket

时间:2016-07-24 17:39:15

标签: java node.js websocket

我尝试从java SE应用程序连接到nodeJS服务器上运行的webSocket。我使用这个https://github.com/TooTallNate/Java-WebSocket库,但是我遇到了问题。我可以连接并从服务器发送消息到客户端,但我不能从客户端到服务器。 这是我使用的代码:

的NodeJS

const WebSocketServer = require('ws').Server
var wss = new WebSocketServer({ server: http })


wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

JAVA

try {
        WebSocketClient mWs = new WebSocketClient( new URI( "ws://localhost:8080" ), new Draft_10() )
        {
            @Override
            public void onMessage( String message ) {
                //JSONObject obj = new JSONObject(message);
                //String channel = obj.getString("channel");
                System.out.println(message);
            }


            @Override
            public void onClose( int code, String reason, boolean remote ) {
                System.out.println( "closed connection" );
            }

            @Override
            public void onError( Exception ex ) {
                ex.printStackTrace();
            }

            @Override
            public void onOpen(ServerHandshake sh) {
                System.out.println( "opened connection" );
            }

        };
        mWs.connect();
        String dog = "dog";
        mWs.send(dog);
        mWs.close();
    } catch (URISyntaxException ex) {
        Logger.getLogger(okno.class.getName()).log(Level.SEVERE, null, ex);
    }

方法send()之后没有任何事情发生。

0 个答案:

没有答案