0
我试图找到这个答案,但大多数例子是纯粹的回声基地套接字服务器。简单的Python套接字服务器没有采取条件语句
基本上我有以下代码:
import socket
import sys
from thread import *
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'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
if data == "hello":
reply = 'OK...Hello back to you'
else:
reply = '01:OK - ' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#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])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
一切都很正常,直到我尝试使用条件语句。我对python非常陌生,我使用它作为一种更好的学习方法,但是当下面的代码行运行时,它会跳过每次的if
。
#Receiving from client
data = conn.recv(1024)
if data == "hello":
reply = 'Why hello there!'
else:
reply = '01:OK - ' + data
if not data:
break
conn.sendall(reply)
从我连接到它的Telnet客户端只是回声的一切,我把它包括'hello'
我送它,而不是短语。
我有一种感觉,它是简单的东西,但我不知道data
变量的格式。
数据将_usually_是你好\ r \ n,但它也可以是H,他,HEL,地狱,你好,你好\ R或打招呼\ r \ n 。这让很多开始的套接字编程人员出现了问题,并导致只有高网络负载或长网络路径才显示的错误。为了解决这个问题,请考虑http://stromberg.dnsalias.org/~strombrg/bufsock.html HTH – user1277476 2014-10-01 23:06:55
这是一个很好的观点,我会做一个增加缓冲的编辑。 – jedwards 2014-10-01 23:14:58
这是完美的,谢谢你们!我知道它必须相当简单。 – Webtron 2014-10-01 23:23:38