Python - 服务器和客户端问题
我正在尝试创建一个基本的服务器和客户端脚本。我的想法是让客户端能够连接到服务器并执行命令。就像SSH那样,但非常简单。以下是我的服务器代码:
import sys, os, socket
host = ''
port = 50103
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w', 0)
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
这是我的客户端:
import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
file.close()
我遇到的问题是这样的。我启动了服务器,然后在同一台机器上运行客户端。我输入端口并连接。接着我看到一个提示符'$'。如果我输入一个命令,比如'ls',客户端就会卡住。我必须退出服务器,客户端才能收到'ls'的输出。顺便说一下,我是在Ubuntu Linux上运行的。不知道这是否重要。
2 个回答
1
首先,你在客户端只连接了一次,而在服务器端每次读取后都关闭了连接。
你应该看看这个例子。
http://ilab.cs.byu.edu/python/socket/echoserver.html
你做了很多事情是不对的。
2
当你在套接字上使用makefile(),然后再用readlines()时,它会一直读取,直到遇到文件结束。在套接字的情况下,文件结束意味着另一端关闭了连接。
在这种情况下,我觉得使用makefile()没有什么意义,尤其是你每次命令后都要创建和关闭它。直接在两端使用send()和recv()就可以了。
你可能还想要有一种实际的“协议”,这样服务器就可以告诉客户端“这里是响应内容”以及“响应结束了”,这样客户端就知道什么时候可以停止等待更多的响应。否则就很难判断什么时候该停止等待了。:)
这里有一个有效的示例:
server.py:
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 50500))
print("Server started")
s.listen(1)
while True:
print "Accepting"
conn, addr = s.accept()
print 'New connection from ', addr
while True:
try:
rc = conn.recv(1024)
print "Command", rc
if not rc.strip():
continue
if rc.strip() == 'END':
print "Close"
conn.send("**END**")
conn.close()
break
else:
conn.send("This is the result of command %s\n" % rc)
except Exception:
conn.close()
sys.exit()
client.py
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50500))
while True:
cmd = raw_input('$ ')
s.send(cmd)
result = s.recv(1024)
print result
if result == "**END**":
print "Ending"
break