LoginSignup
18
14

More than 5 years have passed since last update.

node.js+websocketとProcessingでやりとり

Last updated at Posted at 2016-03-22

環境

mac osx 10.10 yosemite

node.js v0.10.25
ws(node.jsのモジュール インストール方法は下に)

Processing3.0.2(3.0aはエラーでました)
websockets(Processingライブラリ)

環境設定

node.js

https://nodejs.org/en/
http://nodejs.jp/(日本語)

インストール方法は色々なサイトで紹介されています
nvmやnpmも入れると便利です

ws

npm install ws

npmあること前提で、このコマンドでインストールします。

Processing

websockets

Processing内の[Add Library]から検索したらありました
Github https://github.com/alexandrainst/processing_websockets

サンプルコード

サーバ側のnode.js

wsServer.js
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 5000 });

console.log("listening port :5000");

wss.on('connection', function connection(ws) {
    console.log('connection');

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

        ws.send('Hello from ws');
    });

    ws.on('close', function() {
        console.log('close');
    });
});

クライアント側

odeWsSample.pde
import websockets.*;

WebsocketClient wsc;
String message = "";

void setup(){
  size(400,400);

  wsc= new WebsocketClient(this, "ws://localhost:5000");
}

void draw(){
  background(255);
  fill(0);
  text(message, 20, 20);

  if(frameCount % 60 == 0) {
    wsc.sendMessage("Hello from P5");
  }
}

void keyPressed() {
  wsc.sendMessage("press key"+key);
}

void webSocketEvent(String msg){
 println(msg);
 message += msg + "\n";
}

実行

まず、ターミナルからwsServer.jsがあるところまで移動します

$node wsServer.js

nodeを実行し5000番ポートで待ち受けます
次に、Processingのサンプルを実行します
基本ですが、必ずサーバ側から起動してください

無事Processingのスケッチもしくわコンソールとターミナルから各ログが出力されていれば成功です
Processing側でキーボードを押すとターミナルでその文字が出るかと思います

補足的な発展

websocketなのでProcessing以外のものでも可能だし,Processingがサーバ側になることも可能
もちろんProcessing同士でも可能
「localhost」の部分を変更し,サーバ機を別にし遠隔やりとりも可能

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