我写了一个套接字服务器程序员:
#-*- coding:utf-8 -*-
# Author:sele
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
当我在命令中运行它时,会出现错误:
sele-MacBook-Pro:test01 ldl $ ./tests02-server.py
./tests02-server.py:第5行:import:找不到命令
;;连接超时;无法访问服务器
错误:当前平台“ darwin 18”与预期的平台“ darwin 16”不匹配
错误:如果您升级了操作系统,请按照迁移说明进行操作:https://trac.macports.org/wiki/Migration
操作系统平台不匹配
在执行时
“ mportinit ui_options global_options global_variations”
错误:/ opt / local / bin / PORT:初始化MacPorts失败,操作系统平台不匹配
./tests02-server.py:第10行:带有socket.socket(socket.AF_INET,
的意外令牌('
附近的语法错误 socket.SOCK_STREAM)作为s:'
./tests02-server.py: line 10:
为什么找不到import
?
EDIT-01
我将此行插入了第一行。
#!/ usr / bin / env python
当我运行脚本时,出现此错误:
sele-MacBook-Pro:test01 ldl$ ./tests02-server.py
Traceback (most recent call last):
File "./tests02-server.py", line 11, in <module>
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
AttributeError: __exit__
aircrafts-MacBook-Pro:test01 ldl$ ./tests02-server.py
Traceback (most recent call last):
File "./tests02-server.py", line 11, in <module>
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
AttributeError: __exit__
答案 0 :(得分:1)
您将程序作为Shell脚本而不是python程序运行。添加适当的#!
行:
#!/usr/bin/env python
在程序顶部,或者从命令行显式运行它:
$ python tests02-server.py
答案 1 :(得分:0)
您的新问题的答案是您不能将socket.socket(socket.AF_INET, socket.SOCK_STREAM)
与with
一起使用。为了使with
语句可以清理正在使用的资源,该资源的对象必须具有__exit__
方法。 socket.socket(socket.AF_INET, socket.SOCK_STREAM)
返回的内容显然没有__exit__
可以调用的with
方法,因此出现此错误。