我正在学习套接字编程和python。我需要创建一个将命令发送到服务器(list 或 get)的客户端。然后服务器验证该命令。我的客户端程序可以显示 "list" 或 "get" ,但是当我输入其他内容时它不会显示错误消息。
此外,它只能工作一次;当我在收到服务器的回复后输入不同的命令时,它给了我以下错误:
回溯(最后一次调用):文件“fclient.py”,第 49 行,在 client_socket.send(command) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket. py",第 170 行,在 _dummy 引发错误(EBADF,'Bad file descriptor')
我完全迷路了。在客户端程序中获取命令行输入并将其发送到服务器并要求服务器验证命令行参数的最佳方法是什么?有人可以看看并指出我正确的方向吗?非常感谢您的帮助。
客户端.py
import socket #for sockets
import sys #for exit
command = ' '
socksize = 1024
#return a socket descriptor which can be used in other socket related functions
#properties: address family: AF_INET (IP v4)
#properties: type: SOCK_STREAM (connection oriented TCP protocol)
try:
#create an AF_INET, STREAM socket (TCP)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg: #error handling
print 'Failed to create socket. Error code: ' + str(msg[0]) + ', Error message: ' + msg[1]
sys.exit();
print 'Socket Created'
#Get the IP address of the remote host/url
#connect to IP on a certain 'port' using the connect
#host = 'flip3.engr.oregonstate.edu'
#port = 30021
#host = 'www.google.com'
#port = 80
host = '' #symbolic name meaning the local host
port = 8888 #arbitrary non-privileged port
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Existing'
sys.exit()
print 'IP address of ' + host + ' is ' + remote_ip
#Connect to remote server
client_socket.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
while True:
print 'Enter a command: list or get <filename>'
command = raw_input()
if command.strip() == 'quit':
break
client_socket.send(command)
data = client_socket.recv(socksize)
print data
#Close the socket
client_socket.close()
服务器.py
import socket
import sys
from thread import *
#HOST = 'flip3.engr.oregonstate.edu' #symbolic name meaning all available interfaces
#PORT = 30021
HOST = ''
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
server_socket.bind((HOST, PORT)) #bind to a address(and port)
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#put the socket in listening mode
server_socket.listen(10) #maximum 10 connections
print 'TCP Server Waiting for client on port 30021'
#wait to accept a connection - blocking call
client, addr = server_socket.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#keep talking with the client
while 1:
#Receiving from client
data = client.recv(1024)
if (data == 'list' or data == 'get'):
reply = 'receive: ' + data
client.send(reply)
break;
else:
reply = 'wrong command'
client.send(reply)
client.close()