明日のためのプログラムその8。Pythonでsocketサーバクラス
2020-02-03
ということで、前回までのやつをクラスにして、メッセージが来たら処理する関数を渡して実行させてみます。
#-------------------------------------------------------
import sys
import socket
import traceback
import time
#--------------------------------------
class HiraHira:
ABC = 987
#--------------------------
def __init__(self):
self.A = 0
#--------------------------
def setData(selfb):
self.A = 0
#--------------------------
def dispmes(self,s):
print("message:{}".format(s))
#--------------------------
def __enter__(self):
print("前処理")
return self
#--------------------------
def __exit__(self, exc_type, exc_value, traceback):
print("後処理")
#--------------------------
# STATIC
#--------------------------
def dispmes2(s):
print("message2:{}".format(s))
#--------------------------
#--------------------------------------
class hiraSockSv:
dispct = 0
readbuf = 1024
bBlock = False #BlockingMode
address = 'localhost'
port = 12345
dorry = None #
#--------------------------
def setFunc(self,f):
self.dorry = f
#--------------------------
# なんか動いてるっぽい表示
def dispN(self):
if self.dispct==0:
print("●\r",end="")
else:
print("〇\r",end="")
self.dispct = self.dispct + 1;
if self.dispct == 2:
self.dispct = 0
#--------------------------
def __init__(self,address,port):
self.address = address;
self.port = port;
#--------------------------
def setData(self,a,b):
self.address = address;
self.port = port;
#--------------------------
def test(self):
print("A:{} B:{}".format(self.address, self.port))
#--------------------------
def __enter__(self):
#print("前処理")
return self #必須
#--------------------------
def __exit__(self, exc_type, exc_value, traceback):
#print("後処理")
self.tmp = 0
#--------------------------
def localAccept(self,s):
try:
conn, addr = s.accept()
return conn, addr
except Exception as e:
if e.args[0]==10035 or e.args[0]==11:
return None,None
#--------------------------------------
def localRecv(self,conn,n):
try:
dat = conn.recv(n)
return dat
except Exception as e:
if e.args[0]==10035 or e.args[0]==11:
return None
#--------------------------------------
def exec(self):
print("Address:{} Port:{}".format(self.address, self.port))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((self.address, self.port))
s.listen(10)
s.setblocking(False)
while True:
mes = "";
#------------------------------------------------
conn,addr = self.localAccept(s)
if conn==None:
self.dispN()
time.sleep(0.1)
continue
conn.setblocking(False) #LINUXだとこれをしないとrecvがblockingしてしまう
while True:
dat = self.localRecv(conn,self.readbuf)
if not dat:
print("complete?");
break
mes = mes + dat.decode('utf8')
#print(mes);
print("one cours !") #ここでThreadを生成させよう
if self.dorry:
self.dorry(mes)
else:
print("NOT DORRY?")
time.sleep(1)
if not self.bBlock:
conn.sendall(b'complete') #CLIENTに戻す
return 0
#--------------------------------------
#-------------------------------------------------------
if __name__ == '__main__':
def hiraide(mes):
print("-------DORRY-------")
print(mes)
A = HiraHira() # with HiraHira() as A: でもOK
with hiraSockSv('127.0.0.1',12345)as S:
print(".")
# S.setFunc(hiraide) #success
# S.setFunc(A.dispmes) #success
S.setFunc(HiraHira.dispmes2) #success
S.exec()
クライアント
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(('127.0.0.1',12345))
s.sendall('----+----ひらひら1----+----2----+----3----+----4----+----5----+----6'.encode('utf-8'))
data = s.recv(1024)
print(repr(data))
サーバ結果
complete?
one cours !
message2:----+----ひらひら1----+----2----+----3----+----4----+----5----+----6
complete?
one cours !
message2:----+----ひらひら1----+----2----+----3----+----4----+----5----+----6
〇
クライアント結果
b'complete'