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. TP基础

    一.目录结构 解压缩到web目录下面,可以看到初始的目录结构如下: www WEB部署目录(或者子目录)├─index.php 入口文件├─README.md README文件├─Applicatio ...

  2. 28.6 Integer 自动装箱和拆箱

    public class IntegerDemo2 { public static void main(String[] args) { //自动装箱 // Integer i = new Integ ...

  3. 七、环回接口ip地址(逻辑接口)

    loopback接口,在网络设备(一般是路由器)上是一种特殊的接口,它不是物理接口,而是一种看不见摸不着的逻辑接口(也称虚拟接口),但是对于网络设备来说却是至关重要的. 在网络设备上可以通过配置命令来 ...

  4. 智芯微版本的智能配变融合终端交流采集APP

    1.  交采APP基本原理 通过SPI总线周期性的召测交流采集底板的“实时数据”,对“实时数据”变换.加工.统计分析得到“分析数据”和“统计数据”后,通过MQTT总线把这些数据同步到“数据中心”供其他 ...

  5. java 字符串截取 - 最后带上mysql字符串截取比较

    Java中的substring()方法有两个方法的重载,一个带一个参数的,一个带两个参数的. 第一种写法: substring(n);//从索引是n的字符开始截取,条件(n>=0,n<字符 ...

  6. 小说免费看!python爬虫框架scrapy 爬取纵横网

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 风,又奈何 PS:如有需要Python学习资料的小伙伴可以加点击下方 ...

  7. N - Remove Adjacent CodeForces - 1321C

    题目大意:删除字符,当一个字符左边或者右边存在一个比它小“1”的字符那么就可以将这个字符删除,问最多能删除多少个字符 思路,:刚开始想的是,对于单调连续的字符,可以直接删除,比如,单点增的字符只保留前 ...

  8. 65535与TCP连接数的关系测试结论

    首先说结论: .是否有关系 .有关系 对于客户端 -.对于客户端来说,只有65535,因为根据TCP四元组的sport来说,sport只有16位,所以(2^16)-1是65535.也就是最多有6553 ...

  9. Django开发文档-域用户集成登录

    项目概述: 一般在企业中,用户以WINDOWS的域用户统一的管理,所以以Django快速开发的应用,不得不集成AD域登录. 网上一般采用django-python3-ldap的库来做集成登录,但是本方 ...

  10. mongodb权限篇

    1. 权限详解 内建角色: 数据库用户角色: read.readWrite: 数据库管理角色: dbAdmin.dbOwner.userAdmin: 集群管理角色: clusterAdmin.clus ...