2011-12-12 55 views
-1

我是python的新手,我正在尋找一種將1字節字符(例如:字母「D」)發送到IP地址的方法。這是用來控制一個機器人,所以我需要的是向前,向後,向左和向右。我在網上做了一些研究,它建議使用套接字連接到IP地址,但它似乎讓我感到困惑。我已經在我的網頁上做了4個按鈕,但我不太確定如何讓用戶點擊按鈕時網頁發送信號到IP地址(例如:如果用戶按下「右鍵」按鈕,網頁會發送一個字節字符「R」的IP地址)用於發送1字節字符到IP地址的按鈕

任何幫助,將不勝感激

PS會有聯網方法我使用之間有任何大的差別?像wifi和3G之間

+0

忘了提及我將使用tcp/ip作爲客戶端 – user1086652

+0

可能的重複[使用Python注入原始TCP數據包](http://stackoverflow.com/questions/2912123/injecting-raw-tcp-packets-with -python) –

+0

目前還不清楚這與Python有什麼關係。你在使用Python Web框架嗎?如果是這樣,請說明這是哪個框架 - 它可能是相關的。 –

回答

0

插座很容易,特別是在Python! :)

這是一個簡單的程序發送的單個字母的一些IP地址:

import socket 

# Each address on the Internet is identified by an ip-address 
# and a port number. 
robot_ip_address = "192.168.0.12" # Change to applicable 
robot_port  = 3000   # Change to applicable 

# Create a socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# Connect to somewhere... 
s.connect((robot_ip_address, robot_port)) 

# Send one character to the socket 
s.send('D') 

# Close the socket after use 
s.close() 

當然,機器人需要一個類似的計劃接收命令:

import socket 

robot_port = 3000 # Change to applicable 

# Create a socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# "Bind" it to all ip-addresses on the local host, and a specific port 
s.bind(("", robot_port)) 

# Tell the socket to listen for connections 
s.listen(5) 

while True: 
    # Wait for a new connection 
    print "Waiting for connection..." 
    (c, c_addr) = s.accept() 

    print "New connection from: ", c_addr 

    while True: 
     try: 
      command = c.recv(1) 
     except socket.error, e: 
      print "Error: %r" % e 
      break; 

     if command == 'D': 
      # Do something for the 'D' command 
      print "Received command 'D'" 
     elif command == '': 
      print "Connection closed" 
      break 
     else: 
      print "Unknown command, closing connection" 
      break 

    c.close() 

正如你可以看到,有很少的代碼要寫和理解。你不必真正理解網絡和TCP/IP的工作原理,只需要使用套接字通過互聯網進行通信。 :)

複製第一個程序,每個按鈕一個,並修改發送到服務器的內容。然後你有四個程序發送不同的命令,連接到你的按鈕。

閱讀更多關於Python套接字herehere

+0

謝謝,我會研究一下 – user1086652

相關問題