【学习笔记:Python-网络编程】Socket 之初见
Socket 是任何一种计算机网络通讯中最基础的内容。当你在浏览器地址栏中输入一个地址时,你会打开一个套接字,可以说任何网络通讯都是通过 Socket 来完成的。
Socket 的 python 官方函数 http://docs.python.org/library/socket.html
socket和file的区别:
1、file模块是针对某个指定文件进行【打开】【读写】【关闭】
2、socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】
基本流程:
简单的一个端对端单线通信代码如下:
Server:
# -*- coding:utf-8
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(("0.0.0.0",12800))
sock.listen(2)
while True:
conn,sockname = sock.accept()
print("Now,We have accepted a connection from:",sockname)
print("Socket Name is:",conn.getsockname())
print("Socket Peer is:",conn.getpeername())
message = conn.recv(1024)
print("The message we have received is:\n%s"%message)
Client:
# -*- coding:utf-8
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(("127.0.0.1",12800))
sock.send(b"Hello World!")
参数解释:
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): 创建一个套接字对象,所有套接字操作基于此对象进行
family:套接字协议族,包括:有两种类型的套接字:基于文件的和面向网络的。AF表示地址家族(address family)
AF_UNIX:该套接字是基于文件的,一般用于本机通信
AF_INET:该套接字是基于网络的,这也是最常用的(默认)
AF_INET6 :用于第6 版因特网协议(IPv6)寻址
type:套接字类型,常用的有两种:
SOCK_STREAM:流式socket , for TCP (默认)
SOCK_DGRAM:数据报式socket , for UDP
SOCK_RAW :原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
SOCK_RDM :是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
SOCK_SEQPACKET: 可靠的连续数据包服务 proto:协议,与特定的地址家族相关的协议,如果是 0 ,则系统就会根据地址格式和套接类别,自动选择一个合适的协议
sock.bind(address)
sock.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。
sock.listen(backlog)-- 服务端
开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。
backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
这个值不能无限大,因为要在内核中维护连接队列,一般默认值为5
sock.settimeout(timeout)
设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
sock.getpeername()
返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
sock.getsockname()
返回套接字自己的地址。通常是一个元组(ipaddr,port)
sock.fileno()
套接字的文件描述符
sock.setblocking(bool)
是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。
sock.accept()-- 服务端
接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
接收TCP 客户的连接(阻塞式)等待连接的到来
sock.connect(address)-- 客户端
连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
sock.connect_ex(address)
同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061
sock.close()
关闭套接字
sock.recv(bufsize[,flag])
接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。
sock.recvfrom(bufsize[.flag])
与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。
sock.send(string[,flag])
将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。
sock.sendall(string[,flag])
将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。
内部通过递归调用send,将所有内容发送出去。
sock.sendto(string[,flag],address)
将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。
SocketType.__doc__
class SocketType(__builtin__.object)
| socket([family[, type[, proto]]]) -> socket object
|
| Open a socket of the given type. The family argument specifies the
| address family; it defaults to AF_INET. The type argument specifies
| whether this is a stream (SOCK_STREAM, this is the default)
| or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
| specifying the default protocol. Keyword arguments are accepted.
|
| A socket object represents one endpoint of a network connection.
|
| Methods of socket objects (keyword arguments not allowed):
|
| accept() -- accept a connection, returning new socket and client address
| bind(addr) -- bind the socket to a local address
| 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 object identical to the current one [*]
| 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
| makefile([mode, [bufsize]]) -- return a file object for the socket [*]
| 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
| send(data[, flags]) -- send data, may not send all of it
| sendto(data[, flags], addr) -- send data to a given address
| setblocking(0 | 1) -- set or clear the blocking I/O flag
| setsockopt(level, optname, value) -- set socket options
| settimeout(None | float) -- set or clear the timeout
| shutdown(how) -- shut down traffic in one or both directions
|
| [*] not available on all platforms!
|
| Methods defined here: |
| accept(self)
| accept() -> (socket object, address info)
|
| Wait for an incoming connection. Return a new socket representing the
| connection, and the address of the client. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| bind(self, address) | bind(address)
|
| Bind the socket to a local address. For IP sockets, the address is a
| pair (host, port); the host must refer to the local host. For raw packet
| sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
|
| close(self)
| close()
|
| Close the socket. It cannot be used after this call.
|
| connect(self, address)
| connect(address)
|
| Connect the socket to a remote address. For IP sockets, the address
| is a pair (host, port).
|
| connect_ex(self, address)
| connect_ex(address) -> errno
|
| This is like connect(address), but returns an error code (the errno value)
| instead of raising an exception when an error occurs.
|
| fileno(self)
| fileno() -> integer
|
| Return the integer file descriptor of the socket.
|
| getpeername(self)
| getpeername() -> address info
|
| Return the address of the remote endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockname(self)
| getsockname() -> address info
|
| Return the address of the local endpoint. For IP sockets, the address
| info is a pair (hostaddr, port).
|
| getsockopt(self, level, option, buffersize=None)
| getsockopt(level, option[, buffersize]) -> value
|
| Get a socket option. See the Unix manual for level and option.
| If a nonzero buffersize argument is given, the return value is a
| string of that length; otherwise it is an integer.
|
| gettimeout(self)
| gettimeout() -> timeout
|
| Returns the timeout in seconds (float) associated with socket
| operations. A timeout of None indicates that timeouts on socket
| operations are disabled.
|
| ioctl(self, cmd, option)
| ioctl(cmd, option) -> long
|
| Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are
| SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.
| SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).
|
| listen(self, backlog)
| listen(backlog)
|
| Enable a server to accept connections. The backlog argument must be at
| least 0 (if it is lower, it is set to 0); it specifies the number of
| unaccepted connections that the system will allow before refusing new
| connections.
|
| recv(self, buffersize, flags=None)
| recv(buffersize[, flags]) -> data
|
| Receive up to buffersize bytes from the socket. For the optional flags
| argument, see the Unix manual. When no data is available, block until
| at least one byte is available or until the remote end is closed. When
| the remote end is closed and all data is read, return the empty string.
|
| recv_into(self, buffer, nbytes=None, flags=None)
| recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
|
| A version of recv() that stores its data into a buffer rather than creating
| a new string. Receive up to buffersize bytes from the socket. If buffersize
| is not specified (or 0), receive up to the size available in the given buffer.
|
| See recv() for documentation about the flags.
|
| recvfrom(self, buffersize, flags=None)
| recvfrom(buffersize[, flags]) -> (data, address info)
|
| Like recv(buffersize, flags) but also return the sender's address info.
|
| recvfrom_into(self, buffer, nbytes=None, flags=None)
| recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
|
| Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
|
| send(self, data, flags=None)
| send(data[, flags]) -> count
|
| Send a data string to the socket. For the optional flags
| argument, see the Unix manual. Return the number of bytes
| sent; this may be less than len(data) if the network is busy.
|
| sendall(self, data, flags=None)
| sendall(data[, flags])
|
| Send a data string to the socket. For the optional flags
| argument, see the Unix manual. This calls send() repeatedly
| until all data is sent. If an error occurs, it's impossible
| to tell how much data has been sent.
|
| sendto(self, data, flags=None, *args, **kwargs)
| sendto(data[, flags], address) -> count
|
| Like send(data, flags) but allows specifying the destination address.
| For IP sockets, the address is a pair (hostaddr, port).
|
| setblocking(self, flag)
| setblocking(flag)
|
| Set the socket to blocking (flag is true) or non-blocking (false).
| setblocking(True) is equivalent to settimeout(None);
| setblocking(False) is equivalent to settimeout(0.0).
|
| setsockopt(self, level, option, value)
| setsockopt(level, option, value)
|
| Set a socket option. See the Unix manual for level and option.
| The value argument can either be an integer or a string.
|
| settimeout(self, timeout)
| settimeout(timeout)
|
| Set a timeout on socket operations. 'timeout' can be a float,
| giving in seconds, or None. Setting a timeout of None disables
| the timeout feature and is equivalent to setblocking(1).
| Setting a timeout of zero is the same as setblocking(0).
|
| shutdown(self, flag)
| shutdown(flag)
|
| Shut down the reading side of the socket (flag == SHUT_RD), the writing side
| of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
【学习笔记:Python-网络编程】Socket 之初见的更多相关文章
- python 3.x 学习笔记13 (网络编程socket)
1.协议http.smtp.dns.ftp.ssh.snmp.icmp.dhcp....等具体自查 2.OSI七层应用.表示.会话.传输.网络.数据链路.物理 3.socket: 对所有上层协议的封装 ...
- Python网络编程socket
网络编程之socket 看到本篇文章的题目是不是很疑惑,what is this?,不要着急,但是记住一说网络编程,你就想socket,socket是实现网络编程的工具,那么什么是socket,什么是 ...
- Day07 - Python 网络编程 Socket
1. Python 网络编程 Python 提供了两个级别访问网络服务: 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口 ...
- python学习笔记11 ----网络编程
网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...
- python学习笔记10 ----网络编程
网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...
- python网络编程-socket编程
一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...
- python网络编程socket /socketserver
提起网络编程,不同于web编程,它主要是C/S架构,也就是服务器.客户端结构的.对于初学者而言,最需要理解的不是网络的概念,而是python对于网络编程都提供了些什么模块和功能.不同于计算机发展的初级 ...
- Python网络编程-Socket简单通信(及python实现远程文件发送)
学习python中使用python进行网络编程,编写简单的客户端和服务器端进行通信,大部分内容来源于网络教程,这里进行总结供以后查阅. 先介绍下TCP的三次握手: 1,简单的发送消息: 服务器端: i ...
- Day10 Python网络编程 Socket编程
一.客户端/服务器架构 1.C/S架构,包括: 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务)[QQ,SSH,MySQL,FTP] 2.C/S架构与socket的关系: 我们学习soc ...
- Python 网络编程——socket
一 客户端/服务器架构 客户端(Client)服务器(Server)架构,即C/S架构,包括 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务) 理想/目标状态—— 最常用的软件服务器是 ...
随机推荐
- 【python实现卷积神经网络】卷积层Conv2D反向传播过程
代码来源:https://github.com/eriklindernoren/ML-From-Scratch 卷积神经网络中卷积层Conv2D(带stride.padding)的具体实现:https ...
- 数据结构和算法(Golang实现)(14)常见数据结构-栈和队列
栈和队列 一.栈 Stack 和队列 Queue 我们日常生活中,都需要将物品排列,或者安排事情的先后顺序.更通俗地讲,我们买东西时,人太多的情况下,我们要排队,排队也有先后顺序,有些人早了点来,排完 ...
- AJ学IOS(53)多线程网络之NSOperation简介
AJ分享,必须精品 一:简单介绍 1:NSOperation的作⽤使用步骤: 配合使用NSOperation和NSOperationQueue也能实现多线程编程. NSOperation和NSOper ...
- J - Recommendations CodeForces - 1315D
https://blog.csdn.net/w_udixixi/article/details/104479288 大意:n个数,每个数只能向上加,a[i]+1需要的时间是t[i],求使这n个数无重复 ...
- windows下常用快捷指令记忆
快速打开环境变量窗口 sysdm.cpl --系统设置 快速打开远程桌面程序 mstsc ---Microsoft terminal services client 快速打开事件查看器 eventvw ...
- CTO的窘境
做CTO太难了,常年的coding思维让你早已与世隔绝,CTO有很好的技术方案,但CEO.CFO等O听不懂是很麻烦的事.总得来说,做CTO一定要技术背景出身,有很强的沟通能力和情商,敏锐的洞察力和决断 ...
- TensorFlow的模型保存与加载
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf #tensorboard --logdir=&qu ...
- Ubuntu当状态栏网络图标隐藏的解决方法汇总
最有效之一: 直接在终端运行以下命令,以root身份: nm-applet --sm-disable 不建议修改配置文件内容
- Python自学从入门到就业之函数基础(小白必看)
函数介绍 <1>什么是函数 请看如下代码: print(" _ooOoo_ ") print(" o8888888o ") print(" ...
- Nginx+Fastdfs
注: 在配置时,使用非root用户配置 fdfs/fdfs 1. 集群部署 1.1. 准备 创建目录:本文档中所有内容安装到/fdfs目录 [fdfs@5861be93b5b0 /]$mk ...