Ahs*_*aid 4 python sockets websocket python-2.7 python-3.x
编辑格式:
这是原始代码
from __future__ import print_function
import socket
import sys
def socket_accept():
conn, address = s.accept()
print("Connection has been established | " + "IP " + address[0] + "| Port " + str(address[1]))
send_commands(conn)
conn.close()
def send_commands(conn):
while True:
cmd = raw_input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end ="")
def main():
socket_accept()
main()
Run Code Online (Sandbox Code Playgroud)
我收到此错误"TypeError:str()最多需要1个参数(2个给定)"at"client_response"变量
fra*_*ima 15
你有错误:
client_response = str(conn.recv(1024), "utf-8")
Run Code Online (Sandbox Code Playgroud)
只需将其更改为:
client_response = str(conn.recv(1024)).encode("utf-8")
Run Code Online (Sandbox Code Playgroud)
在倒数第二行,你将两个参数传递给str
函数,虽然该str
函数只在Python 2中使用一个参数.事实上,在python 3中最多需要三个参数
https://docs.python.org/2.7/library/functions.html?highlight=str#str https://docs.python.org/3.6/library/functions.html?highlight=str#str
所以你要么试图在python 2解释器中无意中运行python 3代码,要么你正在查看错误的语言文档.
所以要么使用@franciscosolimas的答案,如果你使用的是python 2,要么确保你使用的是python 3,如果是后者,你可能还想添加一个关键字参数,以确保你知道将来会发生什么
client_response = str(conn.recv(1024), encoding="utf-8")
Run Code Online (Sandbox Code Playgroud)