2
8

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 5 years have passed since last update.

通信接続が切れても再度接続待ちに戻るSocket通信をPythonで

Last updated at Posted at 2019-06-01

はじめに

PythonでSocket通信するための情報はまあまあ見つかるけど、Clientからの接続が切れたとき、再度接続待ちに戻るような動作させる方法は、見つからなかった。今回、tryを使って試してみた。ちなみに、Serverがデータを送る設定。

Socket通信

こんな感じ。

Server

Serverかつ送信側。
bind(), listen()で接続の設定して、accept()で接続待ち。
sendall()tryしてだめだったらaccept()に戻る。

server.py
# -*- coding:utf-8 -*-
# tcp/ip socket server
import socket
import time

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    # initialize socket
    s.bind(('127.0.0.1', 50007))
    s.listen(1)
    print("listen")

    while True:
        # wait for a connection
        conn, addr = s.accept()
        print("accept")

        while True:
            # get timestamp
            timestamp = "{}".format(time.perf_counter())
            data = timestamp.encode()

            # send
            try:
                conn.sendall(data)
                print("send data")
                ## sleep
                time.sleep(1)
            except:
                print("connection failed")
                break

Client

Clientかつ受信側。
connect()で接続先を設定。
recv()で受信。

client.py
# -*- coding:utf-8 -*-
# tcp/ip socket client
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    # initialize socket
    s.connect(('127.0.0.1', 50007))

    while True:
        # receive data
        data = s.recv(1024)
        timestamp = float(data.decode())
        print(timestamp)

実行結果

サーバー側はこんな感じ。

$ python .\server.py
listen
accept
send data
send data
send data
connection failed # ここで、クライアントをとめて接続きれた
accept # 再度クライアントを立ち上げた
send data
send data
send data

おわりに

とりあえず、動いた。よかった。
localhostでしかやってないけども。
exceptは、もうちょいちゃんとエラーによって対応変えたほうがいいのかも。
Serverが受信側の場合、どうしたらいいかよくわからん。

参考

pythonでsocket通信を勉強しよう - Qiita

2
8
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
2
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?