2011-12-12 52 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