天天看點

Python---socket庫

  為友善以後查詢和學習,特從常用庫函數和示例來總結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通訊示例  

Python---socket庫
Serve.py
Python---socket庫

#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

Python---socket庫

Client.py

Python---socket庫
#coding:UTF-8

# client
import socket

class Client:

    'Socket Client!'
    
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.addr = (self.ip, self.port)
        print (self.addr)

    def connect(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print (s)
        s.connect(self.addr)

        return s
        #Client.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #print (Client.s)
        #Client.s.connect(self.addr)

if __name__ == "__main__":
    ip = "192.168.3.8"
    port = 1122
    client = Client(ip, port)
    print (client.__doc__)   

    client.connect()

    while True:
        data = input(">")
        if not data:
            break;
        sock.send(data.encode("utf8"))
        print ("發送資訊:%s" %(data))
        if data.upper() == "QUIT":
            break;
    sock.close()        
        
            
    
              

  3. udp示例

Python---socket庫
Python---socket庫
#coding=utf-8

from socket import *
from time import strftime

ip_port=('127.0.0.1',9000)
bufsize=1024

tcp_server=socket(AF_INET,SOCK_DGRAM)
tcp_server.bind(ip_port)

while True:
    msg,addr=tcp_server.recvfrom(bufsize)
    print('===>',msg)
    
    if not msg:
        time_fmt='%Y-%m-%d %X'
    else:
        time_fmt=msg.decode('utf-8')
    back_msg=strftime(time_fmt)

    tcp_server.sendto(back_msg.encode('utf-8'),addr)

tcp_server.close()      
Python---socket庫
Python---socket庫
#coding=utf-8

from socket import *
ip_port=('127.0.0.1',9000)
bufsize=1024

tcp_client=socket(AF_INET,SOCK_DGRAM)

while True:
    msg=input('請輸入時間格式(例%Y %m %d)>>: ').strip()
    tcp_client.sendto(msg.encode('utf-8'),ip_port)

    data=tcp_client.recv(bufsize)

    print(data.decode('utf-8'))

tcp_client.close()