Python---socket库

  为方便以后查询和学习,特从常用库函数和示例来总结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通讯示例  

Serve.py
#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
Client.py
#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()        
        
            
    
        
View Code

  3. udp示例

#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()
View Code
#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()
View Code
posted @ 2018-01-17 15:59  Fate0729  阅读(613)  评论(0编辑  收藏  举报