17
22

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.

Pythonでの再接続可能なServer, Clientの雛形

Posted at

Pythonで簡単なsocketのserver/clientプログラムを書くことが多いのですが、
いつも片方が死んだ時のリコネクト(再接続)の書き方をどうやるんだっけ、となるので、
雛形としてまとめました。

もっとスマートな書き方があればご教示ください。

Server

server.py
#!/usr/bin/python
# coding: utf-8

import socket
import time

host = '127.0.0.1'
port = 65000
buff = 1024

if __name__ == '__main__':

  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind((host, port))

  while True:
    s.listen(1)
    print('Waiting for connection')
    cl, addr = s.accept()
    print('Established connection')
  
    while True:
      try:
        msg = cl.recv(buff)
        print('Received msg: %s' % msg)
        cl.send('c')  # check if connection is alive
        time.sleep(1)
      except socket.error:
        cl.close()
        break

Client

client.py
#!/usr/bin/python
# coding: utf-8

import socket
import time

host = '127.0.0.1'
port = 65000
buff = 1024

def make_connection(host_, port_):
  while True:
    try:
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      sock.connect((host_, port_))
      print('connected')
      return sock
    except socket.error as e:
      print('failed to connect, try reconnect')
      time.sleep(1)

if __name__ == '__main__':
  s = make_connection(host, port)
  while True:
    try:
      s.send('hello')
      # msg = s.recv(buff)
      # print('Client received: %s' % msg)
      time.sleep(1)
    except socket.error as e:
      print('connection lost, try reconnect')
      s = make_connection(host, port)

おしまい

17
22
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
17
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?