1.2socket服务器使用多线程
socket服务器代码如下
# -*- coding: utf-8 -*-
from socket import * import time import threading,_thread as thread myHost = '' #''说明所有IP都可以连接 myPort = 50007 #设置一个端口 socketobj = socket(AF_INET,SOCK_STREAM) #创建TCP对象 socketobj.bind((myHost,myPort)) #绑定端口 socketobj.listen(5) #允许5个请求连接 def now(): return time.ctime(time.time()) def handleClient(connection): #time.sleep(5) while True: data = connection.recv(1024) #每次读取最多1024字节 if not data: break reply = 'Echo=> %s at %s' % (data,now()) #发送数据给客户端 connection.send(reply.encode()) connection.close() def dispatcher(): while True: connection,address = socketobj.accept() #接受数据并打印 print('Server connected by,',address,end='') print('at',now()) #thread.start_new_thread(handleClient,(connection,)) #使用多线程 thread = threading.Thread(target=handleClient,args=(connection,)) #使用多线程 thread.start() #开始线程 dispatcher()
socket客户端代码如下
# -*- coding: utf-8 -*-
from socket import * serverHost = 'localhost' serverPort = 50007 while True: messages = [input('输入').encode()] #输入信息,并设置编码, 可设置b''或者str.encode() socketobj = socket(AF_INET, SOCK_STREAM) # 创建TCP对象 socketobj.connect((serverHost, serverPort)) # 连接端口 for line in messages: socketobj.send(line) data = socketobj.recv(1024) # 从服务器接受信息 print('Client received:', data.decode()) #打印信息,解码打印,str.decode() socketobj.close()