我试图为此找到答案,但大多数示例都是针对纯粹的基于回声的套接字服务器。
基本上我有以下代码:
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
变量的格式。
答案 0 :(得分:1)
非常接近!
Telnet将发送您提供的任何EOL分隔符以及文本。因此,如果您键入"数据"然后按Enter键,data
实际上类似于hello\r\n
。
您可以通过执行更改
等操作来有效地忽略此空白data = conn.recv(1024)
到
data = conn.recv(1024).strip()
你应该好好去。
编辑:
如评论中所述,网络可能会将消息拆分为多个数据包。要解决此问题,您可以使用socket.makefile()
方法获取类似文件的对象,然后使用readline()
,它将阻塞直到完整的行可用。例如,将clientthread
更改为:
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
sfh = conn.makefile("r+b", bufsize=0)
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = sfh.readline().strip()
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()
== PYTHON == Socket created Socket bind complete Socket now listening Connected with 192.168.1.10:42749 == TELNET == $ telnet 192.168.1.106 8888 Trying 192.168.1.106... Connected to 192.168.1.106. Escape character is '^]'. Welcome to the server. Type something and hit enter hello OK...Hello back to you