tcp/socket通信 封装
发送功能,接收功能独立分开
定义server类和client类,可以直接继承使用
后续可以将串口初始化信息,放入配置文件
# 服务器端代码++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from socket import *
import os
from time import ctime
import threading
from cmd import Cmd
class Tcpsersocket(Cmd):
def __init__(self):
self.start_time = ctime()
print('starting ' ,self.start_time)
def conf(self):
print(os.path)
self.host = '127.0.0.1'
self.port = 21567
self.bufsize = 1024
self.addr = (self.host, self.port)
#声明一个socket对象 tcpsersocket
tcpsersock = socket(AF_INET, SOCK_STREAM)
tcpsersock.bind(self.addr)
tcpsersock.listen(5)
quit = False
shutdown = False
print('waiting for connection...')
self.clientsocket, addr = tcpsersock.accept()
print('client connected from: ', addr)
def send(self):
# self.ss = ss
while 1:
self.ss = input("input>>")
self.clientsocket.send(self.ss.encode('utf-8'))
def rec(self):
while 1:
data = self.clientsocket.recv(self.bufsize)
data = data.decode('utf-8')
print('
',ctime(), '
', "rec from client: ", data,'
','press enter to continue')
def main():
x = Tcpsersocket()
x.conf()
t1 = threading.Thread(target=x.send, name="send")
t2 = threading.Thread(target=x.rec, name="rec")
t1.start()
t2.start()
if __name__ =='__main__':
main()
from socket import *
import threading
from cmd import Cmd
class myclientsocket(Cmd):
def __init__(self,host,port,BUFFSIZE):
Cmd.__init__(self)
self.host = host
self.port = port
self.buffsize = BUFFSIZE
self.addr = (self.host, self.port)
def conn(self):
self.clientsocket = socket(AF_INET, SOCK_STREAM)
# 实例名能否和类名 一样呢
self.clientsocket.connect(self.addr)
def rec(self):
while 1:
rdata = self.clientsocket.recv(self.buffsize)
print("rec from ser: ", rdata.decode('utf8'),'
','press enter to continue')
def send(self):
while 1:
data = input('send>')
self.clientsocket.send(data.encode('utf8'))
def main():
y = myclientsocket('127.0.0.1', 21567, 1024)
y.conn()
t1 = threading.Thread(target=y.send, name="send")
t2 = threading.Thread(target=y.rec, name="rec")
t1.start()
t2.start()
if __name__ =='__main__':
main()