"""
服务器程序:
接收客户端输入的字符串,并将字符串的长度回显给客户端
"""
import socket
port = 5555
# 监听来自任何客户端的请求
host = ""
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
# 只接受1个客户端的请求,如果有更多的请求,则处于等待状态
s.listen(1)
print "Server is running on port %d,press CTRL-C to terminate" % port
end = 1
while end:
# 如果有客户端请求,accept返回一个socket和客户端address
clientsocket,clientaddr = s.accept()
print str(clientaddr)
# 使用文件方式
clientfile = clientsocket.makefile("rw",0)
line = clientfile.readline().strip()
clientfile.write("Welcome," + str(clientaddr) + "\n")
# 如果输入空字符串则服务程序退出
if len(line) == 0:end = 0
# 文件必须关闭,socket.close不会负责关闭创建的文件
clientfile.close()
clientsocket.close()
|