1.使用socket模块中socket()函数创建套接字:

socket()函数返回一个socket对象,该对象的方法实现了各种socket系统调用。

语法:

import socket

socket.socket([family[, type[, proto]]])

使用给定的address family, socket type和protocol number创建一个新的socket对象。

The address family(地址家族):AF_INET (默认), AF_INET6,AF_UNIXAF_CAN 或者 AF_RDS

The socket type(套接字类型):SOCK_STREAM (默认), SOCK_DGRAMSOCK_RAW 或者 可能是其他SOCK_常量之一。

The protocol number(协议号):通常是0(这种情况下可以忽略) 或者 CAN_RAW(如果地址家族是AF_CAN)。

注意:AF_CAN family和AF_RDS家族是3.3版本中新增的。

例如:

(1)创建一个TCP/IP套接字

import socket

tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

(2)创建一个UDP/IP套接字

import socket

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

或者为了简写:

from socket import *

tcpSock = socket(AF_INET, SOCK_STREAM)

udpSock = socket(AF_INET, SOCK_DGRAM)

2.套接字对象的方法

(1)服务器端套接字方法:

socket.bind(address)

Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above.)

将套接字绑定到地址。这个套接字必须是没有绑定过的。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。

socket.listen(backlog)

Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0.

监听来自套接字的连接。backlog参数指定最大排队连接数,应至少为0。最大值是依赖于系统的(通常为5),最小值强制为0。

socket.accept()

Accept a connection. The socket must be bound to an address and listening for connections. The return value is 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.

接受一个连接。这个套接字必须已经绑定到一个地址并且正在监听连接。该方法的返回值是一个元组(conn, address),其中conn是一个新的socket对象,该对象在连接时可用于发送和接受数据;address是一个地址,该地址被绑定于在连接另一端的套接字(socket)上。

(2)客户端套接字方法:

socket.connect(address)

Connect to a remote socket at address. (The format of address depends on the address family — see above.)

连接到在address上的远端套接字。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。connect(address)中使用的address地址和bind(address)中是相同的。

socket.connect_ex(address)

Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.

类似于connect(address),但是返回的是一个error indicator替代了通过C级别connect()调用返回针对错误抛出一个异常。如果操作成功,error indicator是0,否则是errno变量的值。这是非常有用的支持,例如,异步连接。

(3)公共用途的套接字方法

socket.recv(bufsize[, flags])

Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

Note:For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

接收来自套接字的数据。该方法的返回值是一个字节对象,它表示已接收到的数据。一次接受的最大数据量被bufsize指定。查看Unix手册recv(2)中可选参数flags的含义;它默认为0。

注意:针对硬件和网络实际情况的最佳匹配,BUFSIZE的值应该是一个相对较小的2的幂,例如,4096。

socket.recvfrom(bufsize[, flags])

Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

接收来自套接字的数据。该方法的返回值是一个元组(bytes, address),其中bytes是一个字节对象,它表示已接受到的数据;address是一个发送数据的套接字的地址。查看Unix手册recv(2)中可选参数flags的含义;它默认为0。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)

socket.send(bytes[, flags])

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO.

发送数据到socket。这个套接字必须连接到一个远端的套接字。可选的flags参数和recv()中有相同的意义。该方法返回发送的字节数目。应用程序负责检查所有数据已经被发送;如果只有部分数据已经被发送,那么应用程序需要尝试发送剩下的数据。关于这个话题的进一步的信息,请查阅the Socket Programming HOWTO。

socket.sendall(bytes[, flags])

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.

发送数据到socket。这个套接字必须连接到一个远端的套接字。可选的flags参数和recv()中有相同的意义。和send()不同,这个方法会连续发送数据(从字节对象)直到所有数据发送完毕或发送错误。成功时返回None。发生错误,会抛出一个异常,如果有数据的话,也没有办法确定有多少数据已经成功发送。

socket.sendto(bytes, address)socket.sendto(bytes, flags, address)

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

发送数据到socket。这个套接字不应该连接到一个远端的套接字,由于目的套接字被地址(address)指定。可选的flags参数和recv()中有相同的意义。该方法返回发送的字节数目。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)

socket.close()

Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

Note:close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().

关闭套接字。在这个套接字上将要进行的所有操作都将失败。远端将不再接收数据(排队的数据刷新后)。当套接字进行垃圾回收是自动关闭。

注意:close()会释放与连接相关的资源,但是不一定立即关闭关联。如果想要及时关闭连接,在调用call()前调用shutdown()。

socket.getpeername()

Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.

返回连接到当前套接字的远端地址。例如,这非常有利于找出一个远端IPv4/IPv6套接字的端口号。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。在许多系统中这个函数不支持。

socket.getsockname()

Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.)

返回当前套接字的地址。例如,这非常有利于找出一个IPv4/IPv6套接字的端口号。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。

socket.getsockopt(level, optname[, buflen])

Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a bytes object. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as byte strings).

返回给定的套接字选项的值。

socket.setsockopt(level, optname, value)

Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a bytes object representing a buffer. In the latter case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module struct for a way to encode C structures as bytestrings).

设置给定的套接字选项的值。

(4)面向阻塞的套接字方法

socket.setblocking(flag)

Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode.

This method is a shorthand for certain settimeout() calls:

  • sock.setblocking(True) is equivalent to sock.settimeout(None)
  • sock.setblocking(False) is equivalent to sock.settimeout(0.0)

设置套接字的阻塞与非阻塞模式:如果flag为false,这个套接字设置为非阻塞模式,否则设置为阻塞模式。

  • sock.setblocking(True)等价于sock.settimeout(None)
  • sock.setblocking(False)等价于sock.settimeout(0.0)

socket.settimeout(value)

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

For further information, please consult the notes on socket timeouts.

设置阻塞套接字操作的超时时间。

socket.gettimeout()

Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() orsettimeout().

得到阻塞套接字操作的超时时间。

(5)面向文件的套接字函数

socket.fileno()

Return the socket’s file descriptor (a small integer). This is useful with select.select().

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation.

返回套接字的文件描述符(一个很小的整数)。

socket.makefile(mode='r'buffering=None*encoding=Noneerrors=Nonenewline=None)

Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). These arguments are interpreted the same way as by the built-in open() function.

Closing the file object won’t close the socket unless there are no remaining references to the socket. The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in a inconsistent state if a timeout occurs.

Note:

On Windows, the file-like object created by makefile() cannot be used where a file object with a file descriptor is expected, such as the stream arguments of subprocess.Popen().

返回一个与套接字相关的文件对象。

socket对象的相关方法的参考官方文档地址:http://docs.python.org/3/library/socket.html#module-socket

转载于:https://www.cnblogs.com/fortwo/archive/2013/04/23/3038123.html

Python网络编程2:创建套接字和套接字对象的内建方法相关推荐

  1. python创建文件对象的函数_Python 文件对象常用内建方法

    学习python教程文件操作时,除了 文件对象读取内容 file.read(size):size为读字节的长度,默认为-1. file.readline(size):逐行读取,如果定义了size参数, ...

  2. 【python网络编程】创建TCP/UDP服务器进行客户端/服务器间通信

    客户端/服务器网络编程介绍 套接字:通信端点 实例:客户端发送数据,接收服务器返回的时间戳 用Python 编写FTP 客户端程序 客户端/服务器网络编程介绍 软件服务器也运行在一块硬件之上,但是没有 ...

  3. Python 网络编程(Socket)

    Python 网络编程(Socket) 一.Socket 套接字 1.Socket 编程 socket本质是编程接口(API),对TCP/IP的封装,提供可供程序员做网络开发所用的接口.Socket ...

  4. Python网络编程(06)----MySQL8.0介绍--01(使用command命令创建数据库以及数据表)

    学习python网络编程最重要的是学会用数据库,数据库的基础知识这里不作介绍,主要讲解使用command命令创建数据库,并往数据库里面插入数据表并查看.然后再用python调用pymysql访问以及操 ...

  5. python网络编程--socket简单实现

    python网络编程                                                                                           ...

  6. python网络编程案例_Python 网络编程_python网络编程基础_python高级编程

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

  7. python网络编程(苦肝一夜,近万字)

    文章目录 一.TCP/IP简介 二.网络设计模块 1.Socket简介 2.python中的socket模块,使用该模块建立服务器需要6个步骤. 1.创建socket对象. 2.将socket绑定(指 ...

  8. 肝!Python 网络编程

    什么是网络? 网络就是一种辅助双方或者多方能够连接在一起,然后可以进行数据传递的工具. 就是为了联通多方然后进行通信用的,即把数据从一方传递给另外一方,为了让在不同的电脑上运行的软件,之间能够互相传递 ...

  9. python网络编程爬虫_Python爬虫--网络编程

    Python 网络编程 Python提供两个基本的Socket模块: Socket,提供了标准的BSD Sockets API SocketServer, 提供了服务器中心类,可以简化网络服务器的开发 ...

最新文章

  1. how to rank conferences or journals?
  2. 小程序 页面禁止左右上下滑动
  3. cad移动时捕捉不到基点_硬盘或移动硬盘认不到时,应该怎样进行故障的检测才正确...
  4. Linux C 存储映射IO
  5. skcket编程实例
  6. CoderForces999D-Equalize the Remainders
  7. linux运行多个c文件路径,linux c的连接库和怎么同时编译多个源程序
  8. 2014计算机中山大学新华学院分数线,中山大学新华学院历年分数线 2021中山大学新华学院录取分数线...
  9. iOS应用开发模板 iOS Boilerplate
  10. php预编译mysql扩展_PHP-Mysqli扩展库的预编译
  11. 【图像压缩】基于matlab JEPG图像压缩【含Matlab源码 1167期】
  12. 计算机专业必备基础知识500题,计算机基础知识500题
  13. ws2812B+单片机驱动
  14. 三大变换与自控(五)三角函数的正交性证明
  15. ANSYS APDL学习(12):如何将ansys求解后的数据(点位移/应力/应变等)导出到txt文件
  16. Python编程题(二)
  17. 智云通CRM:销售就是讲故事?
  18. 部署laravel项目报错:No input file specified.的解决办法
  19. PHP 基础代码之 16 增减变动的操作符 Increment and Decrement Operators
  20. mybatis-plus使用注意事项

热门文章

  1. DOM操作之属性和样式操作
  2. ApacheTomcat解析请求参数的过程
  3. vmware克隆虚拟机
  4. 测试多个线程调用同一静态方法(无静态变量)时是否有线程安全问题
  5. iOS快速集成检查更新
  6. hdu4525 威威猫系列故事——吃鸡腿
  7. 在 iOS 应用中实现飞行模式提醒
  8. libxml2中处理中文
  9. VS2005集成VSS2005的方法
  10. 基于MeanShift的目标跟踪算法及实现