LoginSignup
20
21

More than 5 years have passed since last update.

ServerをNode.js、ClientをJavaでSocket.IO

Last updated at Posted at 2015-09-08

やりたいこと

サーバー側をNode.jsで書いて、
クライアント側ではJavaを使ってSocket.IOで通信したい

サーバー側

server.js
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を使っているので、以下のコマンドでインストールしてください

$ npm install express
$ npm install socket.io

クライアント側

以下のコードではこのライブラリを使ってます
https://github.com/socketio/socket.io-client-java

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

動作

以下のコマンドでサーバーを起動します

$ node server.js

Main.javaを実行するとすぐに「hello, world」とJavaのコンソールに表示されます。その後サーバー側のコンソールには「This is Java」と表示されます。

Node.js

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

Java

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

参考

20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21