# -*- coding: cp936 -*-
"""
TCP服务器创建
1.创建socket
2.绑定主机和端口
3.开始监听
4.准备接收客户端的请求
Windows测试方法
telnet localhost 51423
"""
import socket
# 接受来自任何客户端的请求
host = ""
port = 51423
# 1.创建socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 设置SO_REUSEADDR为1,当关闭socket时,立刻断开
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# 2.绑定主机和端口
s.bind((host,port))
# 3.开始监听
s.listen(5)
while 1:
# 4.准备接收来自客户端的请求
clientsock,clientaddr = s.accept()
print "Got connection from",clientsock.getpeername()
clientsock.close()
|