创建一个echo服务器

时间:2014-02-01 16:59:58

标签: python sockets echo-server

我是python的新手并尝试编码。我想创建简单的echo服务器,即我输入到客户端的任何内容都只是由服务器回显,如果客户端用户按下enter而不写任何内容,则服务器将断开连接。这可能很简单,但我缺乏逻辑,任何帮助??

这是我的代码

#!/usr/bin/env python
import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket
s.bind(("0.0.0.0",12345))   #binding port
s.listen(1) #listening for only one client

print "I am listening..."

conn,addr=s.accept()    #accept the connection

conn.send("\nEnter your name.\n")

data = conn.recv(2048)
print "Client name is : ",data

conn.send("Now each word you typed will be echo back to you.\n")

while len(data)>0:
    data=conn.recv(2048)
    if data == '':
        sys.exit()
    else:   
        conn.send(data)

1 个答案:

答案 0 :(得分:0)

结果将包含换行符,但您只需致电str.strip即可对其进行过滤:

conn.send("\nEnter your name.\n")
data = conn.recv(2048)
if not data.strip():
    print('Please enter a name')
    return 1
print("Client name is : ", data)