# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), port_number))
# become a server socket
serversocket.listen(1)
# accept connection from outside
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a threaded server
while True:
# receive at most 1 byte of data
data = clientsocket.recv(1)
if (not data):
break
do_something_with( data )
在客户端执行以下操作:
# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to the server on specific port
s.connect((server_ip_or_hostname, port_number))
data = get_your_for_bits_as_bytestring()
# send the data until there is no more of them or we lose the socket
while (s and data):
s.sendall(data)
data = get_your_for_bits_as_bytestring()
首先,确保不要每次发送数据时都建立新连接。如果每次运行循环时都重新连接,肯定会给通信增加很多延迟(无论使用什么工具)。此外,根据循环的速度和系统设置的等待时间(这是系统清除未使用的网络连接所需的时间-如果继续以过快的速度打开太多端口,最终会遇到问题,因为将达到最大打开连接数)。你知道吗
您可以在循环外部创建一个套接字,并在循环中写入/读取它—因此连接建立延迟只有一次。你知道吗
现在,根据您的应用程序对时间的要求,您可能需要为通信选择正确的网络协议—4位是非常少的信息量,这些信息被包装在半打层中,其中包含网络协议所需的各种信息:源和目标的网络地址、控制校验和,序列号等,所以每个数据包可以相当大,尽管只包含4位有用的信息。另一方面,如果您运行的不是物联网设备,而是以太网上的计算机,那么您可能不需要关心这一点。你知道吗
也就是说,如果你想尽可能的有效,你可能会希望在尽可能低的水平上发送信息。看看https://docs.python.org/3/howto/sockets.html
快速总结
在服务器端执行以下操作:
在客户端执行以下操作:
相关问题 更多 >
编程相关推荐