socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用【打开】【读写】【关闭】模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)
socket和file的区别:
file模块是针对某个指定文件进行【打开】【读写】【关闭】
一. socket模块
socket,俗称套接字,其实就是一个ip地址和端口的组合。类似于这样的形式(ip, port),其中ip代表的是某个主机,port代表的是某个应用,我们可以通过socket和另外的一台主机进行通信。
关于socket源码的解析在tarnado系列文章中,正在写中。。。。。
1. 通信的方式
tcp通信
udp通信
基于unix的通信
2. socket的方法
# 暂时知道的也就这么多,之后要是在用到其他的我会继续进行保存Methods of socket objects (keyword arguments not allowed): _accept() -- accept connection, returning new socket fd and client address bind(addr) -- bind the socket to a local address 给本地地址绑定一个socket套接字 close() -- close the socket 关闭一个套接字 connect(addr) -- connect the socket to a remote address 连接到远端主机 connect_ex(addr) -- connect, return an error code instead of an exception dup() -- return a new socket fd duplicated from fileno() fileno() -- return underlying file descriptor getpeername() -- return remote address [*] getsockname() -- return local address getsockopt(level, optname[, buflen]) -- get socket options gettimeout() -- return timeout or None listen([n]) -- start listening for incoming connections recv(buflen[, flags]) -- receive data 接受数据 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer) 接受数据到缓冲区中, recvfrom(buflen[, flags]) -- receive data and sender's address recvfrom_into(buffer[, nbytes, [, flags]) -- receive data and sender's address (into a buffer)sendall(data[, flags]) -- send all data 发送数据给远端主机,3.x之后只能发送字节形式,因此在发送的时候一般要进行转换bytes send(data[, flags]) -- send data, may not send all of it 也是发送数据,区别在于send发送的不完整,随机进行发送的,二sendall发送的完整 sendto(data[, flags], addr) -- send data to a given address 基于udp发送数据的 setblocking(0 | 1) -- set or clear the blocking I/O flag 是否设置成阻塞模式0 代表阻塞,1代表非阻塞 setsockopt(level, optname, value) -- set socket options 设置一些socket的桉树 settimeout(None | float) -- set or clear the timeout 设置超时市场 shutdown(how) -- shut down traffic in one or both directions if_nameindex() -- return all network interface indices and names if_nametoindex(name) -- return the corresponding interface index if_indextoname(index) -- return the corresponding interface name [*] not available on all platforms!
查看更多关于Python中对socket的详细介绍的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did81946