zoukankan      html  css  js  c++  java
  • python前后台tcp/udp通讯示例

    以下代码兼容python2.7+、python3

    TCP示例

    服务器 -- sever_tcp.py

    #!/usr/bin/env python
    #coding=utf-8
    
    import time
    import socket
    import threading
    
    local_addr = ('127.0.0.1',8888)
    buff_len = 1024
    
    def conn_proc(sock, addr):
    
        print('accept new connection from %s:%s...' % addr)
        # 发送数据给客户端
        sock.send('welcome'.encode('utf-8'))
    
        while True:
    
            print('wating for message...')
            # 阻塞接收客户端数据
            date = sock.recv(buff_len)
            if not date or date.decode('utf-8')=='exit':
                break 
            print(date.decode('utf-8')) 
    
            time.sleep(1.5)
            sock.send(('server '+str(time.time())).encode('utf-8'))
    
        sock.close()
        print('close connection %s:%s' % addr)
    
    if __name__ == '__main__':
    
        # 创建一个socket
        tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定监听的地址和端口
        tcp.bind(local_addr)
        # 开始监听端口,等待连接的最大数量为10
        tcp.listen(10)
    
        while True:
            # 阻塞等待客户端过来的tcp连接
            sock,addr = tcp.accept()
            # 创建一个新线程来处理TCP连接
            threading.Thread(target=conn_proc,args=(sock,addr)).start()
    
        # 关闭socket   
        tcp.close()

    打印log如下:

    accept new connection from 127.0.0.1:51241...
    wating for message...
    hello server.1563353570.55
    wating for message...
    1563353572.05

    客户端 -- client_tcp.py 

    #!/usr/bin/env python
    #coding=utf-8
    
    import time
    import socket
    
    server_addr = ('127.0.0.1',8888)
    buff_len = 1024
    
    if __name__ == '__main__':
    
        # 创建一个socket
        tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        # 建立连接
        tcp.connect(server_addr)
    
        # 发送数据给服务器
        tcp.send('hello server.'.encode('utf-8'))
        # 阻塞接收服务器数据
        print(tcp.recv(buff_len).decode('utf-8'))
    
        while True:
            tcp.send(str(time.time()).encode('utf-8'))
            date = tcp.recv(buff_len)
            if not date or date.decode('utf-8')=='exit':
                break 
            print(date.decode('utf-8'))
        
        # 关闭socket
        tcp.close()

    打印log如下: 

    welcome
    server 1563353572.051841

    UDP示例

    服务端  -- server_udp.py

    #!/usr/bin/env python
    #coding=utf-8
    
    import time
    import socket
    
    local_addr = ('127.0.0.1',8888)
    buff_len = 1024
    
    if __name__ == '__main__':
    
        # 创建一个socket
        udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 绑定监听的地址和端口
        udp.bind(local_addr)
        
        while True:
    
            print('wating for message...')
            # 阻塞接收客户端数据
            data, addr = udp.recvfrom(buff_len)
            print('received from %s data:%s' % (addr, data.decode('utf-8')))
    
            time.sleep(1.5)
            # 发送数据给客户端
            udp.sendto(('server '+str(time.time())).encode('utf-8'), addr)
    
        # 关闭socket  
        udp.close()

    打印log如下:  

    wating for message...
    received from ('127.0.0.1', 51264) data:hello server.
    wating for message...
    received from ('127.0.0.1', 51264) data:1563353804.57
    wating for message...
    received from ('127.0.0.1', 51264) data:1563353806.07

    客户端  -- client_udp.py

    #!/usr/bin/env python
    #coding=utf-8
    
    import time
    import socket
    
    server_addr = ('127.0.0.1',8888)
    buff_len = 1024
    
    if __name__ == '__main__':
    
        # 创建一个socket
        udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
        # 发送数据给服务器
        udp.sendto('hello server.'.encode('utf-8'), server_addr)
        # 阻塞接收服务器数据
        print(udp.recv(buff_len).decode('utf-8'))
    
        while True:
            udp.sendto(str(time.time()).encode('utf-8'),server_addr)
            print(udp.recv(buff_len).decode('utf-8'))
    
        # 关闭socket
        udp.close()

    打印log如下: 

    server 1563353804.56509
    server 1563353806.0682404

    如果udp连接不通或收发数据延迟,解决办法有2个:

    1. 直接关闭防火墙

    2. disable防火墙中阻止udp的策略规则,并允许python.exe通过防火墙

    在windows上,若想让python隐藏窗口,可在程序启动后,插入如下代码:

    import ctypes
     
    main_wnd = ctypes.windll.kernel32.GetConsoleWindow()    
    if main_wnd != 0:    
        ctypes.windll.user32.ShowWindow(main_wnd, 0)    
        ctypes.windll.kernel32.CloseHandle(main_wnd)
  • 相关阅读:
    7.9学习日志
    7.8学习日志
    7.7学习日志
    未命名 1
    未命名 1
    未命名 1
    【转】搭建Mac OS X下cocos2d-x的Android开发环境
    【转】如何高效利用GitHub——2013-08-28 22
    【转】GitHub删除一个仓库——2013-08-27 21
    【转】Cocos2d-x 2.x CCSprite 灰白图的生成(利用shader设置)——2013-08-27 21
  • 原文地址:https://www.cnblogs.com/kekec/p/11202236.html
Copyright © 2011-2022 走看看