所以我开始研究一种物联网项目,而我遇到的第一个问题就是在设置基本服务器时遇到了麻烦。使用本指南进行一些初始测试,以下是使用的代码:
'''
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一段时间做过这样的事情,它似乎有效......
答案 0 :(得分:0)
代码有效,但不会从客户端发送/接收。以下适度更改使服务器将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 tasty\n') # <==
conn.close()
s.close()
在Linux中使用Netcat进行测试。 (Telnet也应该工作)
$ echo beer | nc -q1 localhost 8888
Connected with 127.0.0.1:37484
beer tasty