2014-10-01 55 views
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变量的格式。

回答

0

非常接近!

Telnet将发送您给它的任何EOL分隔符以及文本。所以如果你输入“data”然后回车,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 
+1

数据将_usually_是你好\ r \ n,但它也可以是H,他,HEL,地狱,你好,你好\ R或打招呼\ r \ n 。这让很多开始的套接字编程人员出现了问题,并导致只有高网络负载或长网络路径才显示的错误。为了解决这个问题,请考虑http://stromberg.dnsalias.org/~strombrg/bufsock.html HTH – user1277476 2014-10-01 23:06:55

+0

这是一个很好的观点,我会做一个增加缓冲的编辑。 – jedwards 2014-10-01 23:14:58

+0

这是完美的,谢谢你们!我知道它必须相当简单。 – Webtron 2014-10-01 23:23:38

相关问题