Python客户端/服务器问题

Aus*_*inM 6 python sockets client command

我正在使用python进行一些项目.我有一个客户端和一个服务器.服务器侦听连接,一旦收到连接,它就等待来自客户端的输入.这个想法是客户端可以连接到服务器并执行系统命令,如ls和cat.这是我的服务器代码:

import sys, os, socket


host = ''                
port = 50105

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)

s.listen(5)
print("Server listening\n")
conn, addr = s.accept()
print 'New connection from ', addr
while (1):
    rc = conn.recv(5)
    pipe = os.popen(rc)
    rl = pipe.readlines()
    file = conn.makefile('w', 0)
    file.writelines(rl[:-1])
    file.close()
    conn.close()
Run Code Online (Sandbox Code Playgroud)

这是我的客户端代码:

import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
cmd = raw_input('$ ')
s.send(cmd) 
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
Run Code Online (Sandbox Code Playgroud)

当我启动服务器时,我得到了正确的输出,说服务器正在监听.但是当我连接我的客户端并键入命令时,服务器退出时出现此错误:

Traceback (most recent call last):
File "server.py", line 21, in <module>
  rc = conn.recv(2)
File "/usr/lib/python2.6/socket.py", line 165, in _dummy
  raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
Run Code Online (Sandbox Code Playgroud)

在客户端,我得到ls的输出,但服务器搞砸了.

Gre*_*ill 6

您的代码调用conn.close()然后循环回来conn.recv(),但conn已经关闭.

  • 作为第三个选项,您可以让*server*在执行命令时生成提示.然后客户端变得非常简单,只是来回传递字符.事实上,在那时你正在重新发明[telnet](http://en.wikipedia.org/wiki/Telnet). (2认同)