2016-01-07 196 views
1

我需要創建一個簡單的服務器來偵聽TCP連接。 如果它接收到文本on<EOF>off<EOF>,則它將發回(回顯)回success。接收部分正在工作,但現在我需要它發回successPython,如何通過TCP發送數據

代碼:

# import threading 
import SocketServer 

class TCPHandler(SocketServer.BaseRequestHandler): 

    def handle(self): 
     self.msg = self.request.recv(1024).strip() 
     if self.msg == "on<EOF>": 
     print "Turning On..." 
     #ECHO "SUCCESS<EOF>"  <----- I need the server to echo back "success" 
     if self.msg == "off<EOF>": 
     print "Turning Off..." 
     #ECHO "SUCCESS<EOF>"  <----- I need the server to echo back "success" 


     if __name__ == "__main__": 
     host, port = '192.168.1.100', 1100 

    # Create server, bind to local host and port 
    server = SocketServer.TCPServer((host,port),TCPHandler) 

    print "server is starting on ", host, port 

    # start server 
    server.serve_forever() 
+0

'>'是否標記應用程序消息的結尾?如果是這樣,閱讀郵件的代碼在哪裏?如果不是,消息如何分隔? –

回答

4

嗯,我做到了以下一個非常好的教程的前一天,無法找到鏈接,但這裏是代碼

client.py

import socket 

host = socket.gethostname() 
port = 12345     # The same port as used by the server 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host, port)) 
s.sendall(b'Hello, world') 
data = s.recv(1024) 
s.close() 
print('Received', repr(data)) 

對於服務器

echo_server.py

import socket 

host = ''  # Symbolic name meaning all available interfaces 
port = 12345  # Arbitrary non-privileged port 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host, port)) 

print host , port 
s.listen(1) 
conn, addr = s.accept() 
print('Connected by', addr) 
while True: 

    try: 
     data = conn.recv(1024) 

     if not data: break 

     print "Client Says: "+data 
     conn.sendall("Server Says:hi") 

    except socket.error: 
     print "Error Occured." 
     break 

conn.close() 
+0

這工作,但最後我結束了使用QT C++ – Ingmar05

+0

它只是來自維基ref:https://wiki.python.org/moin/TcpCommunication – dlewin