python - Python - 显示路径,简单的套接字问题
问题描述
我最近在 3.7 中涉足 python 我想制作一个服务器/客户端,其客户端将显示我输入的路径(macOS):
服务器
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1337 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
info = conn.recv(1024)
print(info)
raw_input("Push to exit")
s.close()
客户 :
import socket
import os
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = os.listdir("/Users/jhon")
s.send(str(info))
s.close()
服务器启动,它正在监听...
python client.py Connected Traceback(最近一次调用最后一次):文件“client.py”,第 10 行,在 s.send(str(info)) 类型错误:需要一个类似字节的对象,而不是 'str'(不明白这),并在客户端启动后,在服务器显示:
- 由 ('127.0.0.1', 52155) b'' Traceback 连接(最近一次调用最后一次):文件“server.py”,第 13 行,在 raw_input(“press for exit”)中 NameError: name 'raw_input' is not defined (venv) MBP-di-Jhon:untitled1 jhon$
解决方案
您在不修改 2.x 代码的情况下从某个 2.x 版本冒险进入 3.7。在继续之前阅读一些有关差异的内容。为了帮助您入门:
替换raw_input
为input
。(可以将 2.x 替换input()
为eval(input())
,但几乎总是应该使用更具体的评估器,例如int(input())
。)
在 3.x 中,字符串是 unicode,而套接字仍然需要字节。改变send
和recv
_
s.send(str(info).encode())
info = conn.recv(1024).decode()
推荐阅读
- reactjs - 如何检测 React js/Solidity 中的变量变化?
- c - C中按位运算的模运算
- javascript - 自动增量不适用于我附加的文本框
- vue.js - Vue如何导入具有相对路径的DXF文件并创建文件对象?
- reactjs - 如何允许将参数字符串传递到 react.js 中的 url
- database - Mongodb按内部元素分组
- java - 将位图图像上传到recyclerview时出现问题
- python-3.x - Python排序列表字段1升序和随机播放字段2
- c++ - 寻求帮助解释 var[x[n]] 的语法
- automation - 失败案例的 TestNg 重新运行