Python的Socket编程

Python的Socket编程

  • 一、Socket简介
  • 二、Socket基本参数和函数介绍
    • 1. socket参数
    • 2.socket相关函数
  • 三、Python编写socket的步骤
    • 1.python编写server的步骤
    • 2.python编写client的步骤
  • 四、python socket变成实操
    • 1.server.py
    • 2.client.py
    • 3.socket更多功能
  • 五、案例
    • 1.TCP
      • 案例一:机器人聊天
      • 案例二:上传文件
    • 2.UDP
      • 案例一:UDP传输
      • 案例二:Web服务应用

一、Socket简介

  socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用打开读写关闭模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)。
  基本上,Socket 是任何一种计算机网络通讯中最基础的内容。例如当你在浏览器地址栏中输入 http://www.cnblogs.com/ 时,你会打开一个套接字,然后连接到 http://www.cnblogs.com/ 并读取响应的页面然后然后显示出来。而其他一些聊天客户端如 gtalk 和 skype 也是类似。任何网络通讯都是通过 Socket 来完成的。
  Python 官方关于 Socket 的函数的介绍:https://docs.python.org/3/library/socket.html

Python的Socket编程_第1张图片

二、Socket基本参数和函数介绍

1. socket参数

  socket函数的使用格式为:socket(family,type[,protocol])

  • 参数一:family 指定应用程序使用的通信协议的协议族,对于TCP/IP协议族,该参数为AF_INET,以下为该参数的一些常用选项
family参数 描述
socket.AF_UNIX 只能够用于单一的Unix系统进程间通信
socket.AF_INET 服务器之间网络通信
socket.AF_INET6 IPv6
  • 参数二:type 是要创建套接字的类型,以下为该参数的一些常用选项
Type参数 描述
socket.SOCK_STREAM 流式socket , 当使用TCP时选择此参数
socket.SOCK_DGRAM 数据报式socket ,当使用UDP时选择此参数
socket.SOCK_RAW 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
  • 参数三:protocol 指明所要接收的协议类型,通常为0或者不填。以下为该参数的一些常用选项
protocol 参数 描述
socket.IPPROTO_RAW 相当于protocol=255,此时socket只能用来发送IP包,而不能接收任何的数据。发送的数据需要自己填充IP包头,并且自己计算校验和
socket.IPPROTO_IP 相当于protocol=0,此时用于接收任何的IP数据包。其中的校验和和协议分析由程序自己完成。

例如:
创建TCP Socket:s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

创建UDP Socket:s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

2.socket相关函数

(1)服务端socket函数

  • s.bind(address):将套接字绑定到地址,在AF_INET下,以tuple(host,prot)的方式传入,如s.bind((host,port))。

  • s.listen(backlog):开始监听TCP传入连接。backlog指定在拒绝连接之前,操作系统可以挂起的最大连接数量。该值最少为1。

  • s.accept():接受TCP连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据,address是连接客户端的地址。(sock,addr = s.accept)。而socket.socket()的这个套接字只是用于监听。

(2)客户端socket函数

  • s.connect(address):链接到address处的套接字,一般address的格式为tuple(host,port),如果链接出错,则返回socket.error错误。

  • s.connect_ex(address):功能与s.connect(address)相同,但成功返回0,失败返回errno的值。

(3)公共Socket函数

  • s.send(string[,flag]):发送TCP数据,将string中的数据发送到连接到套接字,返回值是要发送到字节数量,该数量可能小于string的字节大小。

  • s.sendall(string[,flag]):完整发送TCP数据,将string中的数据发送到链接到套接字,但在返回之前尝试发送所有的数据。成功返回None,失败则抛出异常。

  • s.recv(bufsize[,flag]):接受TCP套接字的数据,数据以字符串的形式返回,bufsize指定要接收的最大数据量,flag提供有关消息的其它消息,通常可以忽略。

  • s.sendto(string[,flag],address):发送UDP数据,将数据发送到套接字,address形式为tuple(hostadder,port),指定远程地址发送,返回值是发送到字节。

  • s.recvfrom(bufsize[,flag]):接受UDP套接字的数据,与recv()类似,但返回值是tuple(data,address)。其中data是包涵接受数据的字符串,address是发送数据的套接字地址。

  • s.close():关闭套接字。

  • s.getpeername():返回套接字的远程地址,返回值通常是一个tuple(hostaddr,port)。

  • s.getsockname():返回套接字自己的地址,返回值通常是一个tuple(hostaddr,port)。

  • s.getsockopt(level,optname[,buflen]]):返回套接字选项的值。

  • s.gettimeout():返回当前超时值,单位是秒,如果没有设置超时值则返回None。

  • s.setsockopt(level, option,value):设置给定套接字选项的值。

  • s.settimeout(timeout):设置套接字操作的超时时间,timeout是一个浮点数,单位是秒。值为None则表示永远不会超时。一般超时期应在刚创建套接字时设置。

  • s.setblocking(flag):如果flag为0,则将套接字设置为非阻塞模式,否则将套接字设置为阻塞模式(默认值)。非阻塞模式下,如果调用recv()没有发现任何数据,或send()调用无法立即发送数据,那么将引发socket.error异常。

  • s.makefile():创建一个与该套接字相关的文件。

  • s.fileno():返回套接字的文件描述。

三、Python编写socket的步骤

1.python编写server的步骤

  1. 第一步是创建socket对象。
    调用socket构造函数。如:
    socket = socket.socket( family, type )
    family参数代表地址家族,可为AF_INET或AF_UNIX。AF_INET家族包括Internet地址,AF_UNIX家族用于同一台机器上的进程间通信。
    type参数代表套接字类型,可为SOCK_STREAM(流套接字)和SOCK_DGRAM(数据报套接字)。
  2. 第二步是将socket绑定到指定地址。
    这是通过socket对象的bind方法来实现的:
    socket.bind( address )
    由AF_INET所创建的套接字,address地址必须是一个双元素元组,格式是(host,port)。host代表主机,port代表端口号。
    如果端口号正在使用、主机名不正确或端口已被保留,bind方法将引发socket.error异常。
  3. 第三步是使用socket套接字的listen方法接收连接请求。
    socket.listen( backlog )
    backlog指定最多允许多少个客户连接到服务器。它的值至少为1。收到连接请求后,这些请求需要排队,如果队列满,就拒绝请求。
  4. 第四步是服务器套接字通过socket的accept方法等待客户请求一个连接。
    connection, address = socket.accept()
    调用accept方法时,socket会时入“waiting”状态。客户请求连接时,方法建立连接并返回服务器。
    accept方法返回一个含有两个元素的元组(connection,address)。
    第一个元素connection是新的socket对象,服务器必须通过它与客户通信;
    第二个元素 address是客户的Internet地址。
  5. 第五步是处理阶段。
    服务器和客户端通过send和recv方法通信(传输 数据)。
    服务器调用send,并采用字符串形式向客户发送信息。send方法返回已发送的字符个数。
    服务器使用recv方法从客户接收信息。调用recv 时,服务器必须指定一个整数,它对应于可通过本次方法调用来接收的最大数据量。
    recv方法在接收数据时会进入“blocked”状态,最后返回一个字符串,用它表示收到的数据。
    如果发送的数据量超过了recv所允许的,数据会被截短。多余的数据将缓冲于接收端。以后调用recv时,
    多余的数据会从缓冲区 删除(以及自上次调用recv以来,客户可能发送的其它任何数据)。
  6. 传输结束,服务器调用socket的close方法关闭连接。

2.python编写client的步骤

  1. 创建一个socket以连接服务器:socket = socket.socket( family, type )
  2. 使用socket的connect方法连接服务器。对于AF_INET家族,连接格式如下:
    socket.connect( (host,port) )
    host代表服务器主机名或IP,port代表服务器进程所绑定的端口号。
    如连接成功,客户就可通过套接字与服务器通信,如果连接失败,会引发socket.error异常。
  3. 处理阶段,客户和服务器将通过send方法和recv方法通信。
  4. 传输结束,客户通过调用socket的close方法关闭连接。

四、python socket变成实操

1.server.py

import socket


if __name__ == '__main__':
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('192.168.16.100', 8001))
    sock.listen(5)
    while True:
        connection,address = sock.accept()
        try:
            connection.settimeout(5)
            buf = connection.recv(1024)
            if buf == '1':
                connection.send('welcome to server!')
            else:
                connection.send('please go out!')
        except socket.timeout:
            print 'time out'
        connection.close()

2.client.py

if __name__ == '__main__':
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('192.168.16.100', 8001))
    import time
    time.sleep(2)
    sock.send('1')
    print sock.recv(1024)
    sock.close()

3.socket更多功能

def bind(self, address): # real signature unknown; restored from __doc__
        """
        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]])
        """
'''将套接字绑定到本地地址。是一个IP套接字的地址对(主机、端口),主机必须参考本地主机。'''
        pass

    def close(self): # real signature unknown; restored from __doc__
        """
        close()
        
        Close the socket.  It cannot be used after this call.
        """
        '''关闭socket'''
        pass

    def connect(self, address): # real signature unknown; restored from __doc__
        """
        connect(address)
        
        Connect the socket to a remote address.  For IP sockets, the address
        is a pair (host, port).
        """
        '''将套接字连接到远程地址。IP套接字的地址'''
        pass

    def connect_ex(self, address): # real signature unknown; restored from __doc__
        """
        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.
        """
        pass

    def detach(self): # real signature unknown; restored from __doc__
        """
        detach()
        
        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.
        """
'''关闭套接字对象没有关闭底层的文件描述符。'''
        pass

    def fileno(self): # real signature unknown; restored from __doc__
        """
        fileno() -> integer
        
        Return the integer file descriptor of the socket.
        """
        '''返回整数的套接字的文件描述符。'''
        return 0

    def getpeername(self): # real signature unknown; restored from __doc__
        """
        getpeername() -> address info
        
        Return the address of the remote endpoint.  For IP sockets, the address
        info is a pair (hostaddr, port).
            """
        '''返回远程端点的地址。IP套接字的地址'''
        pass

    def getsockname(self): # real signature unknown; restored from __doc__
        """
        getsockname() -> address info
        
        Return the address of the local endpoint.  For IP sockets, the address
        info is a pair (hostaddr, port).
        """
        '''返回远程端点的地址。IP套接字的地址'''
        pass

    def getsockopt(self, level, option, buffersize=None): # real signature unknown; restored from __doc__
        """
        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.
        """
        '''得到一个套接字选项'''
        pass

    def gettimeout(self): # real signature unknown; restored from __doc__
        """
        gettimeout() -> timeout
        
        Returns the timeout in seconds (float) associated with socket 
        operations. A timeout of None indicates that timeouts on socket 
        operations are disabled.
        """
        '''返回的超时秒数(浮动)与套接字相关联'''
        return timeout

    def ioctl(self, cmd, option): # real signature unknown; restored from __doc__
        """
        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).
        """
        return 0

    def listen(self, backlog=None): # real signature unknown; restored from __doc__
        """
        listen([backlog])
        
        Enable a server to accept connections.  If backlog is specified, it 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. If not specified, a default reasonable value is chosen.
        """
        '''使服务器能够接受连接。'''
        pass

    def recv(self, buffersize, flags=None): # real signature unknown; restored from __doc__
        """
        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.
        """
'''当没有数据可用,阻塞,直到至少一个字节是可用的或远程结束之前关闭。'''
        pass

    def recvfrom(self, buffersize, flags=None): # real signature unknown; restored from __doc__
        """
        recvfrom(buffersize[, flags]) -> (data, address info)
        
        Like recv(buffersize, flags) but also return the sender's address info.
        """
        pass

    def recvfrom_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__
        """
        recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
        
        Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
        """
        pass

    def recv_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__
        """
        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.
        """
        pass

    def send(self, data, flags=None): # real signature unknown; restored from __doc__
        """
        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.
        """
        '''发送一个数据字符串到套接字。'''
        pass

    def sendall(self, data, flags=None): # real signature unknown; restored from __doc__
        """
        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.
        """
        '''发送一个数据字符串到套接字,直到所有数据发送完成'''
        pass

    def sendto(self, data, flags=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
        """
        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).
        """
        pass

    def setblocking(self, flag): # real signature unknown; restored from __doc__
        """
        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).
        """
'''是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。'''
        pass

    def setsockopt(self, level, option, value): # real signature unknown; restored from __doc__
        """
        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.
        """
        pass

    def settimeout(self, timeout): # real signature unknown; restored from __doc__
        """
        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).
        """
        pass

    def share(self, process_id): # real signature unknown; restored from __doc__
        """
        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().
        """
        return b""

    def shutdown(self, flag): # real signature unknown; restored from __doc__
        """
        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).
        """
        pass

    def _accept(self): # real signature unknown; restored from __doc__
        """
        _accept() -> (integer, address info)
        
        Wait for an incoming connection.  Return a new socket file descriptor
        representing the connection, and the address of the client.
        For IP sockets, the address info is a pair (hostaddr, port).
        """
        pass

五、案例

1.TCP

案例一:机器人聊天

'''服务端'''
import  socketserver


class Myserver(socketserver.BaseRequestHandler):

    def handle(self):

        conn = self.request
        conn.sendall(bytes("你好,我是机器人",encoding="utf-8"))
        while True:
            ret_bytes = conn.recv(1024)
            ret_str = str(ret_bytes,encoding="utf-8")
            if ret_str == "q":
                break
            conn.sendall(bytes(ret_str+"你好我好大家好",encoding="utf-8"))

if __name__ == "__main__":
    server = socketserver.ThreadingTCPServer(("127.0.0.1",8080),Myserver)
    server.serve_forever()


'''客户端'''

import socket

obj = socket.socket()

obj.connect(("127.0.0.1",8080))

ret_bytes = obj.recv(1024)
ret_str = str(ret_bytes,encoding="utf-8")
print(ret_str)

while True:
    inp = input("你好请问您有什么问题? \n >>>")
    if inp == "q":
        obj.sendall(bytes(inp,encoding="utf-8"))
        break
    else:
        obj.sendall(bytes(inp, encoding="utf-8"))
        ret_bytes = obj.recv(1024)
        ret_str = str(ret_bytes,encoding="utf-8")
        print(ret_str)

案例二:上传文件

'''服务端'''

import socket

sk = socket.socket()

sk.bind(("127.0.0.1",8080))
sk.listen(5)

while True:
    conn,address = sk.accept()
    conn.sendall(bytes("欢迎光临我爱我家",encoding="utf-8"))

    size = conn.recv(1024)
    size_str = str(size,encoding="utf-8")
    file_size = int(size_str)

    conn.sendall(bytes("开始传送", encoding="utf-8"))

    has_size = 0
    f = open("db_new.jpg","wb")
    while True:
        if file_size == has_size:
            break
        date = conn.recv(1024)
        f.write(date)
        has_size += len(date)

    f.close()

'''客户端'''

import socket
import os

obj = socket.socket()

obj.connect(("127.0.0.1",8080))

ret_bytes = obj.recv(1024)
ret_str = str(ret_bytes,encoding="utf-8")
print(ret_str)

size = os.stat("yan.jpg").st_size
obj.sendall(bytes(str(size),encoding="utf-8"))

obj.recv(1024)

with open("yan.jpg","rb") as f:
    for line in f:
        obj.sendall(line)

2.UDP

案例一:UDP传输

import socket
ip_port = ('127.0.0.1',9999)
sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)
sk.bind(ip_port)

while True:
    data = sk.recv(1024)
    print data




import socket
ip_port = ('127.0.0.1',9999)

sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)
while True:
    inp = input('数据:').strip()
    if inp == 'exit':
        break
    sk.sendto(bytes(inp,encoding = "utf-8"),ip_port)

sk.close()

案例二:Web服务应用

#!/usr/bin/env python
#coding:utf-8
import socket
  
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, World")
  
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8080))
    sock.listen(5)
  
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()
  
if __name__ == '__main__':
  main()

你可能感兴趣的:(Network,python,网络)