无法读取来自客户端程序的输入
我正在尝试编写客户机 - 服务器代码。 我在客户端代码中添加了一个菜单。 并根据来自客户端的输入,我尝试在服务器代码中添加个案。 我能够将客户选择的选项发送到服务器代码,但无法从接收的数据中选择一个案例。 这是我的代码。
server.py
导入套接字
进口系统
进口操作系统
s1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('socket created s1')
serveraddress =('localhost',2000)
打印('启动服务器',serveraddress)
s1.bind(serveraddress)
s1.listen(3)
而真:
print('waiting for connection')
connection, clientaddress = s1.accept()
print ('connecting with', clientaddress)
command = connection.recv(1000)
print (command)
if command == '1':
print('entered into 1st if')
try:
filename = connection.recv(1000)
with open(filename, 'rb') as filetosend:
for data in filetosend:
connection.sendall(data)
finally:
connection.close()
if command == '2':
print('entered into 2st if')
filelist = os.listdir('C:Rahul')
connection.sendall(filelist)
if command == '3':
print('entered into 3st if')
s1.close()
break
Client.py
进口系统
进口操作系统
导入套接字
s1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serveraddress =('localhost',2000)
打印('连接到服务器'),serveraddress
s1.connect(serveraddress)
尝试:
a = input('Enter you choice: n 1-Get file n 2-Get List n 3-quit n')
while True:
if a == 1:
s1.send('1')
b = input('enter file name: ')
s1.send(b)
downloadDir = r'C:UsersrahulDesktop'
with open(os.path.join(downloadDir, b), 'wb') as filetowrite:
while True:
data = s1.recv(1000)
if not data:
break
filetowrite.write(data)
filetowrite.close()
s1.close()
elif a == 2:
s1.send('2')
#s1.sendall(' send all files list ')
filelist = s1.recv(1000)
print (filelist)
elif a == 3:
x = False
print('closing connection')
s1.close()
最后:s1.close
尝试在客户端脚本中添加except块,您的代码将在此之后生效。 我建议您在套接字中使用raw_input作为输入目的,并在输入处格式化数据类型以避免程序中出现任何错误。
import sys, os, socket s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serveraddress = ('localhost' , 2000) print ('connecting to server on'), serveraddress s1.connect(serveraddress) try: a = int(raw_input('Enter you choice: n 1-Get file n 2-Get List n 3-quit n')) while True: if a == 1: s1.send('1') b = str(raw_input('enter file name: ')) s1.send(b) # downloadDir = 'root' # with open(os.path.join(downloadDir, b), 'wb') as filetowrite: # while True: # data = s1.recv(1000) # if not data: # break # filetowrite.write(data) # filetowrite.close() print "It worked till here." s1.close() elif a == 2: # s1.send('2') # #s1.sendall(' send all files list ') # filelist = s1.recv(1000) # print (filelist) print "It also worked till here." elif a == 3: x = False print "Closing Connection" s1.close() except: print 'It Gave an Error'
这工作得很好。
链接地址: http://www.djcxy.com/p/56439.html