0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでTCPソケット通信サンプル

Posted at

#サーバー側

server.py
import socket
import numpy as np
import time

PORT = 12345

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    host = (socket.gethostbyname(socket.gethostname()))
    print(f"{host = }")
    s.bind((host, PORT))

    while True:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.listen(1)
        print("listen")
        conn, addr = s.accept()
        print("accept")
        i = 0

        while True:
            try:
                print(f"{i*0.04:.03f}")
                i += 1
                data = np.zeros(3*64, dtype="int16")
                conn.sendall(data)
                time.sleep(0.04)

            except KeyboardInterrupt:
                print('Interrupted.')
                break

            except:
                break

#クライアント側

client.py
import socket

HOST = '172.27.128.1'
PORT = 12345

recv_size = 0
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    print(s.connect((HOST, PORT)))

    while 1:
        data = s.recv(1024)
        recv_size += len(data)
        print(len(data), recv_size)

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?