我正在尝试编写客户端 - 服务器代码。我在客户端代码中添加了一个菜单。根据客户端的输入,我尝试在服务器代码中添加案例。我能够将客户端选择的选项发送到服务器代码,但无法从接收的数据中选择案例。这是我的代码。
server.py
[sys_]name_to_handle_at()
Client.py
import socket
import sys
import os
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print (' socket created s1')
serveraddress = ('localhost' , 2000)
print ('starting server on', serveraddress)
s1.bind(serveraddress)
s1.listen(3)
while True:
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
答案 0 :(得分:1)
尝试在客户端脚本中添加除块以外的代码,之后您的代码将起作用。 我建议你在套接字中使用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'
这很好。