Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

やりたいこと

サーバー側を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

参考

nwtgck
最近はScrapbox → https://scrapbox.io/nwtgck
https://scrapbox.io/nwtgck
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした