所以我开始从事一种物联网项目,我遇到的第一个问题是在设置基本服务器时遇到问题。使用本指南,要进行一些初始测试,以下是正在使用的代码:
'''
Simple socket server using threads
'''
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
我可以设置服务器,它会在套接字上侦听,但当我尝试使用telnet连接时,它会超时。既然我在大学里上网,这会是事情没有进展的原因吗?我记得不久前在C中做过这样的事情,当时它似乎起作用。。。
代码可以工作,但不会从客户端发送/接收。以下适度的更改使服务器向任何幸运的客户端发送beer tasty
。
来源
'''
Simple socket server using threads
'''
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
conn.send('beer tastyn') # <==
conn.close()
s.close()
在Linux中使用Netcat进行测试。(Telnet也应该工作)
试验
$ echo beer | nc -q1 localhost 8888
Connected with 127.0.0.1:37484
beer tasty