Python编程:socket模块

简介: Python编程:socket模块

p41.1.png

基础介绍

socket:对底层的封装,实现接收和发送能功能

发送:send

接收:receive


ISO七层

应用层 http,smtp, dns, ftp,ssh,snmp,ping,dhcp

表示层

会话层

传输

网络层 ip

数据链路层 mac

物理层


TCP/IP 三次握手,四次断开

UDP


port最大 65535


会话实例

# 服务器端
import socket
server = socket.socket()
server.bind(("localhost", 6969)) #绑定监听端口
server.listen(5)  # 监听
print("监听开始..")
while True:
    conn, addr = server.accept()  #等待连接
    print("conn:", conn, "\naddr:", addr)  # conn连接实例
    while True:
        data = conn.recv(1024)  # 接收
        if not data:
            print("connect close..")
            break
        print(data.decode("utf-8"))  # 解码
        conn.send(data.upper())  # 发送
server.close()

参数说明:

AF_INET:IPv4协议
AF_INET6: IPv6协议
SOCK_STREAM:面向流的TCP协议
SOCK_DGRAM: 面向无连接UDP协议


# 客户端
import socket
client = socket.socket()  #生成socket连接对象
ip_port =("localhost", 6969)  # 地址和端口号
client.connect(ip_port)  # 连接
while True:
    content = input(">>")
    if not content:  # 如果传入空字符会阻塞
        print("connect close..")
        break
    client.send(content.encode("utf-8"))  #传送和接收都是bytes类型
    data = client.recv(1024)  # 接收
    print(data.decode("utf-8"))  # 解码
client.close()

help(socket)

"""
 class socket(_socket.socket)
     |  A subclass of _socket.socket adding the makefile() method.
     |  
     |  Method resolution order:
     |      socket
     |      _socket.socket
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __enter__(self)
     |  
     |  __exit__(self, *args)
     |  
     |  __getstate__(self)
     |  
     |  __init__(self, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, proto=0, fileno=None)
     |  
     |  __repr__(self)
     |      Wrap __repr__() to reveal the real class name and socket
     |      address(es).
     |  
     |  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).
     |  
     |  close(self)
     |  
     |  detach(self)
     |      detach() -> file descriptor
     |      
     |      Close the socket object without closing the underlying file descriptor.
     |      The object cannot be used after this call, but the file descriptor
     |      can be reused for other purposes.  The file descriptor is returned.
     |  
     |  dup(self)
     |      dup() -> socket object
     |      
     |      Duplicate the socket. Return a new socket object connected to the same
     |      system resource. The new socket is non-inheritable.
     |  
     |  get_inheritable(self)
     |      Get the inheritable flag of the socket
     |  
     |  makefile(self, mode='r', buffering=None, *, encoding=None, errors=None, newline=None)
     |      makefile(...) -> an I/O stream connected to the socket
     |      
     |      The arguments are as for io.open() after the filename,
     |      except the only mode characters supported are 'r', 'w' and 'b'.
     |      The semantics are similar too.  (XXX refactor to share code?)
     |  
     |  set_inheritable(self, inheritable)
     |      Set the inheritable flag of the socket
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  family
     |      Read-only access to the address family for this socket.
     |  
     |  type
     |      Read-only access to the socket type.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from _socket.socket:
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  bind(...)
     |      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]])
     |  
     |  connect(...)
     |      connect(address)
     |      
     |      Connect the socket to a remote address.  For IP sockets, the address
     |      is a pair (host, port).
     |  
     |  connect_ex(...)
     |      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(...)
     |      fileno() -> integer
     |      
     |      Return the integer file descriptor of the socket.
     |  
     |  getpeername(...)
     |      getpeername() -> address info
     |      
     |      Return the address of the remote endpoint.  For IP sockets, the address
     |      info is a pair (hostaddr, port).
     |  
     |  getsockname(...)
     |      getsockname() -> address info
     |      
     |      Return the address of the local endpoint.  For IP sockets, the address
     |      info is a pair (hostaddr, port).
     |  
     |  getsockopt(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      recvfrom(buffersize[, flags]) -> (data, address info)
     |      
     |      Like recv(buffersize, flags) but also return the sender's address info.
     |  
     |  recvfrom_into(...)
     |      recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
     |      
     |      Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
     |  
     |  send(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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(...)
     |      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).
     |  
     |  share(...)
     |      share(process_id) -> bytes
     |      
     |      Share the socket with another process.  The target process id
     |      must be provided and the resulting bytes object passed to the target
     |      process.  There the shared socket can be instantiated by calling
     |      socket.fromshare().
     |  
     |  shutdown(...)
     |      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).
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from _socket.socket:
     |  
     |  proto
     |      the socket protocol
     |  
     |  timeout
     |      the socket timeout
"""
相关文章
|
29天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
29天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
29天前
|
Python
Python网络编程基础(Socket编程) 使用try-except处理网络错误
【4月更文挑战第11天】在网络编程中,错误处理和异常管理是非常重要的部分。网络操作经常因为各种原因而失败,比如网络断开、服务器无响应、地址不正确等。因此,学会如何使用Python的异常处理机制来捕获和处理这些错误,是编写健壮的网络应用的关键。
|
1月前
|
网络协议 网络安全 Python
Python网络编程基础(Socket编程) 错误处理和异常
【4月更文挑战第10天】网络编程涉及到很多复杂的操作和潜在的风险,如连接失败、数据丢失、超时等问题。因此,正确的错误处理和异常捕获是确保网络程序稳定性和可靠性的关键。本章将介绍网络编程中常见的错误和异常,并探讨如何在Python中进行有效的错误处理。
|
1月前
|
存储 Python
Python网络编程基础(Socket编程) UDP 发送和接收数据
【4月更文挑战第10天】对于UDP客户端而言,发送数据是一个相对简单的过程。首先,你需要构建一个要发送的数据报,这通常是一个字节串(bytes)。然后,你可以调用socket对象的`sendto`方法,将数据报发送到指定的服务器地址和端口。
|
28天前
|
网络协议 Linux Python
Python网络编程基础(Socket编程)epoll在Linux下的使用
【4月更文挑战第12天】在上一节中,我们介绍了使用`select`模块来实现非阻塞IO的方法。然而,`select`模块在处理大量并发连接时可能会存在性能问题。在Linux系统中,`epoll`机制提供了更高效的IO多路复用方式,能够更好地处理大量并发连接。
|
2天前
|
存储 算法 网络协议
【探索Linux】P.26(网络编程套接字基本概念—— socket编程接口 | socket编程接口相关函数详细介绍 )
【探索Linux】P.26(网络编程套接字基本概念—— socket编程接口 | socket编程接口相关函数详细介绍 )
9 0
|
16天前
|
网络协议 Linux Go
Go语言TCP Socket编程(下)
Go语言TCP Socket编程
|
16天前
|
网络协议 Ubuntu Unix
Go语言TCP Socket编程(上)
Go语言TCP Socket编程
|
16天前
|
存储 网络协议 关系型数据库
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信