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 之初见的更多相关文章

  1. python 3.x 学习笔记13 (网络编程socket)

    1.协议http.smtp.dns.ftp.ssh.snmp.icmp.dhcp....等具体自查 2.OSI七层应用.表示.会话.传输.网络.数据链路.物理 3.socket: 对所有上层协议的封装 ...

  2. Python网络编程socket

    网络编程之socket 看到本篇文章的题目是不是很疑惑,what is this?,不要着急,但是记住一说网络编程,你就想socket,socket是实现网络编程的工具,那么什么是socket,什么是 ...

  3. Day07 - Python 网络编程 Socket

    1. Python 网络编程 Python 提供了两个级别访问网络服务: 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口 ...

  4. python学习笔记11 ----网络编程

    网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...

  5. python学习笔记10 ----网络编程

    网络编程 网络编程需要知道的概念 网络体系结构就是使用这些用不同媒介连接起来的不同设备和网络系统在不同的应用环境下实现互操作性,并满足各种业务需求的一种粘合剂.网络体系结构解决互质性问题彩是分层方法. ...

  6. python网络编程-socket编程

     一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...

  7. python网络编程socket /socketserver

    提起网络编程,不同于web编程,它主要是C/S架构,也就是服务器.客户端结构的.对于初学者而言,最需要理解的不是网络的概念,而是python对于网络编程都提供了些什么模块和功能.不同于计算机发展的初级 ...

  8. Python网络编程-Socket简单通信(及python实现远程文件发送)

    学习python中使用python进行网络编程,编写简单的客户端和服务器端进行通信,大部分内容来源于网络教程,这里进行总结供以后查阅. 先介绍下TCP的三次握手: 1,简单的发送消息: 服务器端: i ...

  9. Day10 Python网络编程 Socket编程

    一.客户端/服务器架构 1.C/S架构,包括: 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务)[QQ,SSH,MySQL,FTP] 2.C/S架构与socket的关系: 我们学习soc ...

  10. Python 网络编程——socket

    一 客户端/服务器架构 客户端(Client)服务器(Server)架构,即C/S架构,包括 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务) 理想/目标状态—— 最常用的软件服务器是 ...

随机推荐

  1. Array(数组)对象-->概念和创建

    1.什么是数组? 数组对象是使用单独的变量名来存储一系列的值. 2.数组创建的三种方法: 方法1:常规方式 var arr=new Array(); arr[0]="lisa"; ...

  2. pinpoint php 使用不当引发棘手的问题 --psid sid tid pname ptype ah

    Pinpoint 简单介绍 Pinpoint 是用 Java 编写的 APM(应用性能管理)工具,用于大规模分布式系统,以帮助分析系统的总体结构以及分布式应用程序的组件之间是如何进行数据互联的. 安装 ...

  3. 刮刮乐自定义view

    说明:该代码是参考鸿洋大神的刮刮乐自定义view来写的. 实现:刮刮乐-刮奖的效果,如下效果 下面直接放代码了:只有一个自定义view,要实现真正的功能还需要进一步封装 /** * 自定义view-刮 ...

  4. Ant安装与配置

    1. 到apache 官网去下载最新版本的ant,http://ant.apache.org/:下载后直接解压缩到电脑上,不需要安装: 2.环境变量配置: 2.1 ->计算机右键->属性- ...

  5. Gallery实现图片拖动切换

    Gallery中文意思为画廊,通过Gallery能够实现用手指在屏幕上滑动实现图片的拖动.效果如下: 上面,为了学习了解,只用了android默认的Icon图片. 主程序中创建了一个继承自BaseAd ...

  6. sqli-labs通关----11~20关

    第十一关 从第十一关开始,就开始用post来提交数据了,我们每关的目的都是获取users表下password字段的内容. post是一种数据提交方式,它主要是指数据从客户端提交到服务器端,例如,我们常 ...

  7. L22 Data Augmentation数据增强

    数据 img2083 链接:https://pan.baidu.com/s/1LIrSH51bUgS-TcgGuCcniw 提取码:m4vq 数据cifar102021 链接:https://pan. ...

  8. X - Ehab and Path-etic MEXs CodeForces - 1325C

    MMP,差一点就做对了. 题目大意:给你一个树,对这个树的边进行编号,编号要求从0到n-1,不可重复,要求MEX(U,V)尽可能的小, MEX(x,y)的定义:从x到y的简单路径上,没有出现的最小编号 ...

  9. B2 - TV Subscriptions (Hard Version)

    题目连接:https://codeforces.com/contest/1247/problem/B2 题解:双指针,,一个头,一个尾,头部进入,尾部退出,一开始先记录1到k,并记录每个数字出现的次数 ...

  10. 今天我们来讨论一下CSS3属性中的transition属性;

    transition属性是CSS3属性:顾名思义英文为过渡的意思:主要有四个值与其一一对应:分别是property(CSS属性名称),duration过渡的时长,timimg-function转速曲线 ...