为方便以后查询和学习,特从常用库函数和示例来总结socket库

  Python---socket库

1. 术语

family:AF_INET

socktype:SOCK_STREAM或SOCK_DGRAM

protocol:IPPROTO_TCP

2. 常用库函数

(1). socket()

  #创建socket

(2). gethostname()

  #返回主机名 

  >>>>USER-20170820ND

(3). gethostbyname(hostname)

  #根据主机名得到IP

   >>>>192.168.3.8

(4). gethostbyname_ex(hostname)

  #根据主机名返回一个三元组(hostname, aliaslist, ipaddrlist)

  >>>> ('USER-20170820ND', [], ['192.168.3.8'])

(5). gethostbyaddr(ip_addr)

  #返回一个三元组(hostname, aliaslist, ipaddrlist)

  >>>> ('USER-20170820ND.ws325', [], ['192.168.3.8'])

(6). getservbyname(servicename[, protocolname])

  #返回端口号

  port = socket.getservbyname("http", "tcp")

  >>>> 80

(7). getprotobyname()

  ppp = socket.getprotobyname("tcp")  

  >>>> 6

(8). getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)

(9). ntohs() ntohl()

  #将网络字节序转换为主机字节序

(10). htons() htonl()

  #将主机字节序转换为网络字节序

(11). inet_aton()

(12). inet_ntoa()

(13). getdefaulttimeout()

  #得到设置的时间超时

(14). setdefaulttimeout()

  #设置时间超时

 3. Serve和Client通讯示例  

#coding:UTF-8

import socket  #导入socket库

class Serve:
    'Socket Serve!!!'

    #设置退出条件
    stop = False

    def __init__(self):
        hostname = socket.gethostname()
        print (hostname)
        self.ip = socket.gethostbyname(hostname)
        self.port = 1122
        self.addr = (self.ip,self.port)
        print (self.addr)

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print (s)

        s.bind(self.addr)
        s.listen(5)

        while not self.stop:
            print('等待接入,侦听端口:%s -- %d' % (self.ip, self.port))
            clientsocket, clientaddr = s.accept()
            print ("接入成功:%s--%d" %(clientaddr[0], clientaddr[1]))

            while True:
                
                try:
                    buff = clientsocket.recv(1024)
                    print ("接收数据:%s" %(buff))
                except:
                    clientsocket.close()
                    break;
                if not buff:
                    print ("not buff!!!")
                    break;

                self.stop=(buff.decode('utf8').upper()=="QUIT")
                if self.stop:
                    print ("响应退出命令!")
                    break
            clientsocket.close()
        s.close()    
        
             
if __name__ == "__main__":
    serve = Serve()
    
View Code

相关文章:

  • 2021-04-19
  • 2021-11-16
  • 2021-10-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-06-01
相关资源
相似解决方案