Python编程:socket模块

简介: Python编程:socket模块

image.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
"""

相关文章
|
1月前
|
人工智能 数据可视化 数据挖掘
探索Python编程:从基础到高级
在这篇文章中,我们将一起深入探索Python编程的世界。无论你是初学者还是有经验的程序员,都可以从中获得新的知识和技能。我们将从Python的基础语法开始,然后逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。最后,我们将通过一些实际的代码示例,来展示如何应用这些知识解决实际问题。让我们一起开启Python编程的旅程吧!
|
1月前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。
|
1月前
|
Unix Linux 程序员
[oeasy]python053_学编程为什么从hello_world_开始
视频介绍了“Hello World”程序的由来及其在编程中的重要性。从贝尔实验室诞生的Unix系统和C语言说起,讲述了“Hello World”作为经典示例的起源和流传过程。文章还探讨了C语言对其他编程语言的影响,以及它在系统编程中的地位。最后总结了“Hello World”、print、小括号和双引号等编程概念的来源。
117 80
|
1月前
|
Python
Python Internet 模块
Python Internet 模块。
125 74
|
26天前
|
Python
[oeasy]python055_python编程_容易出现的问题_函数名的重新赋值_print_int
本文介绍了Python编程中容易出现的问题,特别是函数名、类名和模块名的重新赋值。通过具体示例展示了将内建函数(如`print`、`int`、`max`)或模块名(如`os`)重新赋值为其他类型后,会导致原有功能失效。例如,将`print`赋值为整数后,无法再用其输出内容;将`int`赋值为整数后,无法再进行类型转换。重新赋值后,这些名称失去了原有的功能,可能导致程序错误。总结指出,已有的函数名、类名和模块名不适合覆盖赋新值,否则会失去原有功能。如果需要使用类似的变量名,建议采用其他命名方式以避免冲突。
41 14
|
18天前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
26 3
|
1月前
|
分布式计算 大数据 数据处理
技术评测:MaxCompute MaxFrame——阿里云自研分布式计算框架的Python编程接口
随着大数据和人工智能技术的发展,数据处理的需求日益增长。阿里云推出的MaxCompute MaxFrame(简称“MaxFrame”)是一个专为Python开发者设计的分布式计算框架,它不仅支持Python编程接口,还能直接利用MaxCompute的云原生大数据计算资源和服务。本文将通过一系列最佳实践测评,探讨MaxFrame在分布式Pandas处理以及大语言模型数据处理场景中的表现,并分析其在实际工作中的应用潜力。
87 2
|
1月前
|
小程序 开发者 Python
探索Python编程:从基础到实战
本文将引导你走进Python编程的世界,从基础语法开始,逐步深入到实战项目。我们将一起探讨如何在编程中发挥创意,解决问题,并分享一些实用的技巧和心得。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考。让我们一起开启Python编程的探索之旅吧!
59 10
|
1月前
|
IDE 程序员 开发工具
Python编程入门:打造你的第一个程序
迈出编程的第一步,就像在未知的海洋中航行。本文是你启航的指南针,带你了解Python这门语言的魅力所在,并手把手教你构建第一个属于自己的程序。从安装环境到编写代码,我们将一步步走过这段旅程。准备好了吗?让我们开始吧!
|
1月前
|
关系型数据库 开发者 Python
Python编程中的面向对象设计原则####
在本文中,我们将探讨Python编程中的面向对象设计原则。面向对象编程(OOP)是一种通过使用“对象”和“类”的概念来组织代码的方法。我们将介绍SOLID原则,包括单一职责原则、开放/封闭原则、里氏替换原则、接口隔离原则和依赖倒置原则。这些原则有助于提高代码的可读性、可维护性和可扩展性。 ####

热门文章

最新文章