简体   繁体   中英

create an echo server

I am new to python and trying to code. I want to create simple echo server ie whatever I input to the client will simply be echo back by the server and if the client user press enter without writing anything then the server will disconnects. It may be very simple but I lacks logic here, any help??

here is my code

#!/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)

The result will contain a newline, but you can simply call str.strip to filter that out:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM