C/S架构:
客户端/服务端
套接字:
通信端点,在进行通讯之前先创建套接字
socket模块:
socket()函数创建套接字,语法规则:
socket(socket family,socket_type,protocol=0)#示例:创建TCP/IP套接字socket(socket.AF INET,socket.SOCK_STREAM)
服务器端套接字对象的方法:
bind()——绑定地址(ip+端口)到套接字
listen()——开启Tcp监听
accept()——被动接收TCP客户端连接
客户端套接字对象方法:
connect()——主动初始化TCP服务器连接
connect_ex()——功能同上+出错时返回错误代码,而不是抛出异常
流程:
from socket import *import timeHOST=""PORT=2333BUFSIZE=1024ADDR=(HOST,PORT)tcpServer=socket(AF_INET,SOCK_STREAM)tcpServer.bind(ADDR)tcpServer.listen(5)while True:print ("waitting for connection....")tcpClient,addr=tcpServer.accept()print("connection from:",addr)while True:data=tcpClient.recv(BUFSIZE)if not data:breakprint("[%s] %s"%(time.ctime(),data))tcpClient.send("[%s] %s"%(time.ctime(),data))tcpServer.close()tcpClient.close()
