发送1字节字符到IP地址的按钮

-1 投票
1 回答
2675 浏览
提问于 2025-04-17 08:12

我刚开始学习Python,想找个办法把一个字节的字符(比如字母"D")发送到一个IP地址。这是用来控制机器人的,所以我只需要前进、后退、左转和右转这几个指令。我在网上查了一些资料,发现可以用套接字(sockets)来连接到这个IP地址,但对我来说有点复杂。我已经在我的网页上做了四个按钮,但不太确定怎么让网页在用户点击按钮时发送信号到IP地址(比如:如果用户按下“右转”按钮,网页就会发送一个字节的字符“r”到这个IP地址)

任何帮助都非常感谢

另外,我用的网络方式会有很大区别吗?比如WiFi和3G之间的差别

1 个回答

1

使用套接字很简单,特别是在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套接字的内容,可以在这里这里查看。

撰写回答