Python—socket库建议收藏

为方便以后查询和学习,特从常用库函数和示例来总结socket库1.术语family:AF_INETsocktype:SOCK_STREAM或SOCK_DGRAMprotocol:IPPROT

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

全栈程序员社区此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“验证码”,获取验证码。在微信里搜索“全栈程序员社区”或者“www_javaforall_cn”或者微信扫描右侧二维码都可以关注本站微信公众号。

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

View Code

  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()

View Code

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()

View Code

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120224.html原文链接:https://javaforall.net

(0)
上一篇 2021年12月18日 下午1:00
下一篇 2021年12月18日 下午1:00


相关推荐

  • clion 2021 激活码_最新在线免费激活

    (clion 2021 激活码)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html…

    2022年3月26日
    55
  • AI工具大揭秘:小白也能玩转大模型,收藏这篇就够了!

    AI工具大揭秘:小白也能玩转大模型,收藏这篇就够了!

    2026年3月19日
    2
  • android之Unable to execute dex: Multiple dex files define「建议收藏」

    出现了异常Dex Loader:Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl; 查了好多方法都不行,最后得到了解决方法:

    2022年3月11日
    40
  • automake 框架_GNU Automake

    automake 框架_GNU AutomakeAutomake 是一个从文件 Makefile am 自动生成 Makefile in 的工具 每个 Makefile am 基本上是一系列 make 的宏定义 make 规则也会偶尔出现 生成的 Makefile in s 服从 GNUMakefile 标准 GNUMakefile 标准文档 参见 GNU 编码标准中的 Makefile 惯例 节 长 复杂 而且会发生改变 Automake 的目的就是解除个人

    2026年3月18日
    2
  • Mac 如何强制关机?「建议收藏」

    Mac 如何强制关机?「建议收藏」在通常情况下,MacOSX是非常稳定的,但是它偶尔也会发点小脾气,出现应用程序没有响应的情况。如果你正在运行的应用程序失去响应,强制退出一般都能解决,但是偶尔也会出现整个系统都失去响应,鼠标不能用,这时候你只能强制关机了。楼主使用Mac2年多了,只遇到过一次死机哈。下面介绍两种强制关机的解决办法:1、不用学就明白的,跟windows一样的,长按电源键不放,五秒之后电脑就会强行切断电源。不过它有个坏处,就是可能会损坏系统文件,所以建议不要使用这种方法。2、同时按住control+.

    2022年6月26日
    53
  • 最稳定asp空间websamba完美攻略

    最稳定asp空间websamba完美攻略转载自鹏程网络 http www 6882 com 空间 30m asp ftp 评价 最快最稳定的免费 ASP 空间 freehost21 4cpu ASP 脚本解释和运算速度测试 整数运算测试 进行 50 万次加法运算 完成时间 238 毫秒 浮点运算测试 进行 20 万次开方运算 完成时间 218 毫秒 asp 探针 http www websamba com uxxxxu asp asphttp www w

    2026年3月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号