Python客户端/服务器问题 [英] Python client / server question

查看:193
本文介绍了Python客户端/服务器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the client can connect to the server and execute system commands such as ls and cat. This is my server code:

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()

这是我的客户端代码:

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())


b $ b

当我启动服务器时,我得到正确的输出,说服务器正在侦听。但是当我与我的客户端连接并输入命令时,服务器会退出并显示以下错误:

When I start the server I get the right output, saying the server is listening. But when I connect with my client and type a command the server exits with this error:

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

,我得到ls的输出,但服务器搞砸了。

On the client side, I get the output of ls but the server gets screwed up.

推荐答案

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

Your code calls conn.close() and then loops back around to conn.recv(), but conn is already closed.

这篇关于Python客户端/服务器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆