一个小型服务器
import socket
s=socket.socket()
host=socket.gethostname()port=12304 #获得当前主机名并设置端口s.bind((host,port)) #把主机与端口使用socket.bind()方法绑定到socket套接字上PRint(host,port)s.listen(5) #对这个socket进行监听 while True: c , addr=s.accept() print("Got connection from",addr) c.send('Thank you'.encode())c.close()
一个小型客户机
import sockets=socket.socket()
host=socket.gethostname()#获取当前主机名port = 12304print(host,port) s.connect((host,port)) print(s.recv(1024))
首先需要开启两个shell来分别运行服务器和客户机,不然会一直报错
python3使用的是Unicode编码,而socket.send()发送的却是bite 所以需要使用.encode()进行转换
新闻热点
疑难解答