LoginSignup
20
21

More than 5 years have passed since last update.

PythonからProcessingへソケット通信でデータを送る

Last updated at Posted at 2017-07-14

概要

簡単にプロトタイピングをするときに、ややこしい処理をPythonに、描画をProcessingに任せると楽に作れる。良い連携の仕方を探してたら、ソケット通信でシンプルに作れた。もっと良い方法があったら教えてください。

コード

PythonからProcessingへ、一方的にテキストメッセージを送るだけのコードを、サンプルとして以下に。Processing側を先に立ち上げて、続けてPython側を実行すると、Processingの標準出力にメッセージを出力する。

Processing(受信側)

conenctWithPython.pde
import processing.net.*;

int port = 10001; // 適当なポート番号を設定

Server server;

void setup() {
  server = new Server(this, port);
  println("server address: " + server.ip()); // IPアドレスを出力
}

void draw() {
  Client client = server.available();
  if (client !=null) {
    String whatClientSaid = client.readString();
    if (whatClientSaid != null) {
      println(whatClientSaid); // Pythonからのメッセージを出力
    } 
  } 
}

Python(送信側)

toProcessing.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

host = "127.0.0.1" #Processingで立ち上げたサーバのIPアドレス
port = 10001       #Processingで設定したポート番号

if __name__ == '__main__':
    socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #オブジェクトの作成
    socket_client.connect((host, port))                               #サーバに接続

    #socket_client.send('送信するメッセージ')                #データを送信 Python2
    socket_client.send('送信するメッセージ'.encode('utf-8')) #データを送信 Python3

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