首页 > 解决方案 > 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()
  1. 服务器启动,它正在监听...

  2. python client.py Connected Traceback(最近一次调用最后一次):文件“client.py”,第 10 行,在 s.send(str(info)) 类型错误:需要一个类似字节的对象,而不是 'str'(不明白这),并在客户端启动后,在服务器显示:

  3. 由 ('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$

标签: pythonsockets

解决方案


您在不修改 2.x 代码的情况下从某个 2.x 版本冒险进入 3.7。在继续之前阅读一些有关差异的内容。为了帮助您入门:

替换raw_inputinput。(可以将 2.x 替换input()eval(input()),但几乎总是应该使用更具体的评估器,例如int(input())。)

在 3.x 中,字符串是 unicode,而套接字仍然需要字节。改变sendrecv_

s.send(str(info).encode())
info = conn.recv(1024).decode()

推荐阅读