python tcp server
基本思路:
1、指定IP、端口号;
2、绑定;
3、开启监听;
4、接受连接创建socket;
5、收发数据
参考来源 python tcp server 连接多个客户端
# coding=utf-8
# !/usr/bin/env python
import socket
import time
import threading
ServerIP = "21.23.34.45"
BroadcastIP = "0.0.0.0"
ServerPort = 6543
BUFSIZ = 1024
ADDR = (BroadcastIP , ServerPort)
strPrint = ''
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind(ADDR)
tcpServer.listen(2)
clientSocketList = [] # 放每个客户端的socket
def Writer(strText):
with open('log.log', 'a+', encoding='utf-8') as f:
f.write(strText)
iTextLength = len(strText)
if iTextLength > 120:
f.write('\n')
def Recv():
while True:
for clinet in clientSocketList:
try:
dataRecv = clinet[0].recv(BUFSIZ) # 到这里程序继续向下执行
except Exception as e:
continue
if not dataRecv:
clientSocketList.remove(clinet)
strTime = time.strftime('\n%Y-%m-%d %H:%M:%S-')
strPrint = "{}:disconnect".format(clinet[1])
strPrint = strTime + strPrint
print(strPrint)
Writer(strPrint)
print(strPrint)
Writer(strPrint)
continue
else:
strTime = time.strftime('\n%Y-%m-%d %H:%M:%S-')
strRecv = "from {} recv len={}, data={}".format(clinet[1], len(dataRecv), dataRecv)
strPrint = strTime + strRecv
print(strPrint)
Writer(strPrint)
def CheckClient():
print("{}:{}".format(ServerIP, ServerPort))
strPrint = 'waiting for connecting...'
strTime = time.strftime('\n%Y-%m-%d %H:%M:%S-')
strPrint = strTime + strPrint
print(strPrint)
Writer(strPrint)
while True:
clientSock, addr = tcpServer.accept()
strTime = time.strftime('\n%Y-%m-%d %H:%M:%S-')
strPrint = 'connected from: {}'.format(addr)
strPrint = strTime + strPrint
print(strPrint)
Writer(strPrint)
clientSock.setblocking(0)
clientSocketList.append([clientSock, addr])
def Send():
while True:
try:
strPrint = "\n{}:{}".format(ServerIP, ServerPort)
print(strPrint)
user_input = input('>>>')
# print("from server send len={}, data={}".format(len(user_input), user_input))
for clintTemp in clientSocketList:
if user_input == '1':
clintTemp[0].send(b'\x66\x66\x66')
elif user_input == '2':
clintTemp[0].send(b'\x66\x66\x66')
elif user_input == '3':
clintTemp[0].send(b'\x66\x66\x66')
elif user_input == '4':
clintTemp[0].send(b'\x66\x66\x66')
elif user_input == '5':
clintTemp[0].send(b'\x66\x66\x66')
elif user_input == '6':
clintTemp[0].send(b'\x66\x66\x66')
# conn.send(input_bytes) # 循环发送消息
# conn.close()
except Exception as e:
print(e)
if __name__ == '__main__':
threadRecv = threading.Thread(target=Recv) # 子线程
threadRecv.start()
threadCheckClient = threading.Thread(target=CheckClient) # 子线程
threadCheckClient.start()
threadSend = threading.Thread(target=Send) # 子线程
threadSend.start()