TCP Socket 编程 实现 多线程
实现功能:
1.多线程,同时可以连接多个客户端
2.将客户端上传的数据,以十六进制的方式,保存在文件中
3.为每一个IP建立一个文件夹,根据时间戳建立文件,并将数据写入其中
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#多线程连接socket,并将发送的数据以16进制的方式保存在相应的文件夹中
import socket # 导入 socket 模块
import time
import os
import threading
record ="./record/"
#host = "172.31.3.11" #socket.gethostname() # 获取本地主机名
host = "192.168.1.5"
port = 8081
#获取时间戳
def get_record_time():
now = int(time.time())
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d_%H_%M_%S", timeArray)
record_time = otherStyleTime + '.txt'
return record_time
#十六进制保存数据
def hex_data_save(record_file,save_data):
try :
fp = open(record_file , 'a+')
except BaseException as msg:
if not os.path.exists(record_file):
#将文件夹与与文件分离
filepath, _ = os.path.split(record_file)
#创建文件夹
os.makedirs(filepath)
fp = open(record_file , 'a+')
fp.write(save_data.hex())
fp.write('\n')
fp.close()
def thread_process(client_socket,client_addr,record_file):
while True:
recv_data = client_socket.recv(1024)
if not recv_data:
break
hex_data_save(record_file,recv_data)
client_socket.close()
#监听TCP链接
def tcp_listen():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 创建 socket 对象
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 允许socket地址复用,防止出现 address alread use 问题
s.bind((host, port)) # 绑定端口
s.listen(5)
while True:
c,addr = s.accept() # 建立客户端连接
#print(addr ,"link sucess")
record_file = record + str(addr[0])+str(addr[1]) +"/"+ get_record_time()
# 开启线程
thd = threading.Thread(target=thread_process, args=(c, addr,record_file))
thd.daemon=True
thd.start()
#关闭socket连接
if __name__ == "__main__":
tcp_listen()