【发布时间】:2017-05-22 16:27:58
【问题描述】:
我正在尝试编写客户端-服务器代码。我在客户端代码中添加了一个菜单。并且根据来自客户端的输入,我尝试在服务器代码中添加案例。我能够将客户端选择的选项发送到服务器代码,但无法从接收到的数据中选择一个案例。这是我的代码。
server.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
Client.py
import sys
import os
import socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serveraddress = ('localhost' , 2000)
print ('connecting to server on'), serveraddress
s1.connect(serveraddress)
try:
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:\Users\rahul\Desktop'
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()
finally:
s1.close
【问题讨论】:
标签: python sockets server network-programming client-server