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)
おしまい