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
"""
相关文章
|
10月前
|
开发者 Python
Python Socket编程:不只是基础,更有进阶秘籍,让你的网络应用飞起来!
在数字时代,网络应用成为连接世界的桥梁。Python凭借简洁的语法和丰富的库支持,成为开发高效网络应用的首选。本文通过实时聊天室案例,介绍Python Socket编程的基础与进阶技巧。基础篇涵盖服务器和客户端的建立与数据交换;进阶篇则探讨多线程与异步IO优化方案,助力提升应用性能。通过本案例,你将掌握Socket编程的核心技能,推动网络应用飞得更高、更远。
154 1
|
9月前
|
Python
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
使用Python的socket库实现客户端到服务器端的图片传输,包括客户端和服务器端的代码实现,以及传输结果的展示。
312 3
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
|
9月前
|
JSON 数据格式 Python
Socket学习笔记(一):python通过socket实现客户端到服务器端的文件传输
本文介绍了如何使用Python的socket模块实现客户端到服务器端的文件传输,包括客户端发送文件信息和内容,服务器端接收并保存文件的完整过程。
426 1
Socket学习笔记(一):python通过socket实现客户端到服务器端的文件传输
|
8月前
|
Kubernetes 网络协议 Python
Python网络编程:从Socket到Web应用
在信息时代,网络编程是软件开发的重要组成部分。Python作为多用途编程语言,提供了从Socket编程到Web应用开发的强大支持。本文将从基础的Socket编程入手,逐步深入到复杂的Web应用开发,涵盖Flask、Django等框架的应用,以及异步Web编程和微服务架构。通过本文,读者将全面了解Python在网络编程领域的应用。
125 1
|
9月前
|
消息中间件 监控 网络协议
Python中的Socket魔法:如何利用socket模块构建强大的网络通信
本文介绍了Python的`socket`模块,讲解了其基本概念、语法和使用方法。通过简单的TCP服务器和客户端示例,展示了如何创建、绑定、监听、接受连接及发送/接收数据。进一步探讨了多用户聊天室的实现,并介绍了非阻塞IO和多路复用技术以提高并发处理能力。最后,讨论了`socket`模块在现代网络编程中的应用及其与其他通信方式的关系。
754 3
|
9月前
|
安全 网络协议 网络安全
Python Socket编程大揭秘:从菜鸟到黑客的进阶之路,你准备好了吗?
【10月更文挑战第4天】在编程领域,Python Socket编程犹如一把开启网络世界的钥匙,带领开发者从简单数据传输迈向复杂应用构建。本文将引导你从零开始,逐步掌握Socket编程的核心技巧,包括基本概念、TCP服务器与客户端的搭建、并发处理及异常管理、SSL/TLS加密通信,直至深入了解网络协议与安全漏洞。通过实战演练与理论学习,助你成为驾驭网络世界的高手。
92 1
|
9月前
|
存储 网络协议 Linux
聊一聊 Python 的 socket,以及 select、poll、epoll 又是怎么一回事?
聊一聊 Python 的 socket,以及 select、poll、epoll 又是怎么一回事?
510 2
|
10月前
|
监控 网络协议 数据库连接
Python3 监控端口:使用 socket 库
Python3 监控端口:使用 socket 库
143 1
|
10月前
|
网络协议 Python
告别网络编程迷雾!Python Socket编程基础与实战,让你秒变网络达人!
在网络编程的世界里,Socket编程是连接数据与服务的关键桥梁。对于初学者,这往往是最棘手的部分。本文将用Python带你轻松入门Socket编程,从创建TCP服务器与客户端的基础搭建,到处理并发连接的实战技巧,逐步揭开网络编程的神秘面纱。通过具体的代码示例,我们将掌握Socket的基本概念与操作,让你成为网络编程的高手。无论是简单的数据传输还是复杂的并发处理,Python都能助你一臂之力。希望这篇文章成为你网络编程旅程的良好开端。
123 3
|
10月前
|
网络协议 Python
网络世界的建筑师:Python Socket编程基础与进阶,构建你的网络帝国!
在数字宇宙中,网络如同复杂脉络连接每个角落,Python Socket编程则是开启这一世界的钥匙。本文将引导你从基础概念入手,逐步掌握Socket编程,并通过实战示例构建TCP/UDP服务器与客户端。你将学会使用Python的socket模块进行网络通信,了解TCP与UDP的区别,并运用多线程与异步IO提升服务器性能。跟随本文指引,成为网络世界的建筑师,构建自己的网络帝国。
68 2

推荐镜像

更多