2014-07-12 3 views
0

tcpclient에서 매개 변수를 사용하거나 사용하지 않고 함수를 호출하는 더 나은 방법을 찾고 있습니다. 정해진 길은 보이지 않습니다.매개 변수가있는 Python Tcp 서버 호출 함수

현재 무엇을하고 있습니다. 클라이언트 측에서

내가 좋아하는 문자열을 보내

server#broadcast#helloworld 

서버에서 :

commands = [] 
    data = self.request.recv(BUFF) 
    commands = data.split('#') 
    if commands[0] == 'server': 
     if commands[1] == 'stop': 
      serverStop() 
     if commands[1] == 'broadcast': 
      sendtoall(commands[2]) 

    if commands[0] == 'application': 
     if commands[1] == 'doStuff': 
      doStuff(commands[2], commands[3]) 

클라이언트에서 A는 명령 # 하위 명령 #의 PARM 번호 문자열을 보내 parm을 실행 한 다음 서버 측에서 분할하여 함수를 호출하십시오. 이 방법이 효과적이지만 호출 함수와 오류 검사는 매우 빠르게 중복됩니다.

오류를 서버 측에서 계속 확인하고 싶습니다. 매개 변수가 있거나없는 함수와 매개 변수의 양과 함께 작동해야합니다.

클라이언트에서 함수를 호출하는 더 좋은 방법이 있다면 공유하십시오. 읽어 주셔서 감사합니다.

+1

주입니다 또 다른'if'. – beetea

+0

tcpclient에 사용중인 프로토콜이 있습니까? 상태 저장 프로토콜인가요 아니면 스테이트리스 프로토콜입니까? – AlexLordThorsen

답변

1

수행하려는 작업과 네트워크 프로토콜의 모양에 따라 프로그램을 다르게 구성해야합니다. 이 예제에서는 사용자 정의 상태 비 저장 프로토콜을 사용하고 있다고 가정합니다.

commands = [] 
data = self.request.recv(BUFF) 
commands = data.split('#') 
process_commands(commands) 

def process_commands(commands): 
    """ 
    Determines if this is a server or application command. 
    """ 
    if commands[0] == 'server': 
     process_server_command(commands[1:]) 
    if commands[0] == 'application': 
     process_application_command(commands[1:]) 

def process_server_command(commands): 
    """ 
    because I truncated the last list and removed it's 0 element we're 
    starting at the 0 position again in this function. 
    """ 
    if commands[0] == 'stop': 
     serverStop() 
    if commands[0] == 'broadcast': 
     sendtoall(commands[1]) 

def process_application_command(commands) 
    if commands[0] == 'doStuff': 
     doStuff(commands[1], commands[2]) 

이 구조체는 중첩 된 if 문을 제거하고 코드의 제어 경로가 무엇인지 쉽게 볼 수있게합니다. 또한 tryexcept 블록을 훨씬 쉽게 추가 할 수 있습니다 (직선 소켓을 사용하는 경우 필요합니다).

0

왜 RPC 프로토콜을 사용하지 않습니까? 이 경우 문자열을 파싱 할 필요가 없습니다. 여기

는`IF-elif` 블록을 사용하는 대신`다음 if`에 의해 위의 코드에서 불필요한 검사를 피할 수 있습니다 서버

from SimpleXMLRPCServer import SimpleXMLRPCServer 

def add(a, b): 
    return a+b 

server = SimpleXMLRPCServer(("localhost", 1234)) 
print "Listening on port 1234..." 
server.register_function(add, "add") 
server.serve_forever() 

그리고 클라이언트

import xmlrpclib 
print 'start' 
proxy = xmlrpclib.ServerProxy("http://localhost:1234/") 
print "3 + 4 is: %s" % str(proxy.add(3, 4)) 
관련 문제