pythontcp服务器框架_python TCP服务器/客户端, UDP服务器/客户端框架

创建一个TCP服务器:

from socket import *

ss = socket(AF_INET/AF_LOCAL, SOCK_STREAM)                       #创建服务器套接字

ss.bind()                                                                                            #把地址绑定到套接字上

ss.listen()                                                                                           #监听连接

inf_loop:                                                                                            #服务器无限循环,等待连接请求

cs = ss.accept()                                                                           #接受客户端连接

comm_loop:                                                                                 #通信循环

cs.recv()/cs.send()                                                                  #对话(接收与发送)

cs.close()                                                                                     #关闭客户端套接字

ss.close()                                                                                        #关闭服务器套接字

创建一个TCP客户端:

cs = socket()                                                                                 #创建客户端套接字

cs.connect()                                                                                #连接到服务器

comm_loop:                                                                                #通信循环

cs.send()/cs.recv()                                                                #对话(发送/接收)

cs.close()                                                                                  #关闭客户端

其中,accept():return either None or a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection

创建一个UDP服务器:

ss = socket()

ss.bind()

inf_loop:

cs = ss.recvfrom()/ss.sendto()

ss.close()

创建一个UDP客户端:

cs = socket()

comm_loop:

cs.sendto()/cs.recvfrom()

cs.close()

其中,由于UDP是无连接的,所以就不需要调用listen()函数来监听进来的连接了。同时,由于UDP是无连接的,所以无法把客户端连接交给另外的套接字进行后续的通讯(即不能调用accept()函数)。关于socket.sendto(string[, flags], address),socket.recvfrom(bufsize[, flags])函数的参数和返回值请参考python帮助文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值