首页 > 编程 > Python > 正文

python3 socket 服务器和客户机小问题

2019-11-11 02:06:29
字体:
来源:转载
供稿:网友

一个小型服务器

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()进行转换


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表