服务器作为Node.js,客户端作为Java Socket.IO


我想做什么

使用Node.js编写服务器端,
在客户端,我想使用Java

与Socket.IO通信

服务器端

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.sockets.on('connection', function (socket){
  // hello, worldはクライアントが接続するとすぐに1度だけ送信されます
  socket.emit('message_from_server', 'hello, world');

  // クライアントからmessage_from_clientがemitされた時
  socket.on('message_from_client', function (msg){
    console.log('message:', msg);
  });
});

我正在使用express和socket.io,因此请使用以下命令安装

1
2
$ npm install express
$ npm install socket.io

客户端

以下代码使用此库
https://github.com/socketio/socket.io-client-java

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import java.net.URISyntaxException;

public class Main {
    public static void main(String[] args) throws URISyntaxException {

        final Socket socket = IO.socket("http://localhost:3000");

        // サーバーからのmessage_from_serverがemitされた時
        socket.on("message_from_server", new Emitter.Listener() {
            @Override
            public void call(Object... objects) {
                // 最初の引数を表示
                System.out.println(objects[0]);
                //サーバー側にmessage_from_clientで送信
                socket.emit("message_from_client", "This is Java");

            }
        });

        socket.connect();
    }
}

操作

使用以下命令启动服务器

1
$ node server.js

一旦运行

Main.java,就会在Java控制台中看到" hello,world"。然后服务器端控制台将显示" This is Java"。

Node.js

スクリーンショット 2015-09-08 午前10.31.07.png

Java

スクリーンショット 2015-09-08 午前10.32.51.png

参考

  • http://socket.io/get-started/chat/
  • https://github.com/socketio/socket.io-client-java