• Python中的网络编程


    TCPServer端:

    __author__ = 'Nature'
    # -*- coding: utf-8 -*-
    from socket import *
    from time import ctime
    HOST = ''
    PORT = 21567
    BUFSIZ=1024
    ADDR = (HOST,PORT)
    
    tcpserver = socket(AF_INET,SOCK_STREAM)
    tcpserver.bind(ADDR)
    tcpserver.listen(5)
    
    while True:
        print("waiting for connection....")
        tcpclient ,addr = tcpserver.accept()
        print('...connected from:',addr)
        while True:
            data = tcpclient.recv(BUFSIZ)
            if not data:
                break
            tcpclient.send(('[%s]%s'%(ctime(),data)).encode())
        tcpclient.close()
    tcpserver.close()
    

    TCPclient端:

    __author__ = 'Nature'
    # -*- coding: utf-8 -*-
    from socket import *
    
    HOST ='127.0.0.1'
    PORT = 21567
    BUFSIZE = 1024
    ADDR = (HOST,PORT)
    
    tcpclient = socket(AF_INET,SOCK_STREAM)
    tcpclient.connect(ADDR)
    
    while True:
        data = input('>')
        if not data:
            break
        tcpclient.send(data.encode())
        data = tcpclient.recv(BUFSIZE)
        if not data:
            break
        print(data)
    tcpclient.close()
    

    UDPserver端:

    __author__ = 'Nature'
    # -*- coding: utf-8 -*-
    from socket import *
    from time import ctime
    HOST = ''
    PORT = 21567
    BUFSIZ=1024
    ADDR = (HOST,PORT)
    
    tcpserver = socket(AF_INET,SOCK_DGRAM)
    tcpserver.bind(ADDR)
    
    while True:
        print("waiting for message....")
        tcpclient ,addr = tcpserver.recvfrom(BUFSIZ)
        tcpserver.sendto(('[%s]%s'%(ctime(),tcpclient)).encode(),addr)
        print('...receive from and returned to:',addr)
    tcpserver.close()
    

      

    UDPclient端:

    __author__ = 'Nature'
    # -*- coding: utf-8 -*-
    from socket import *
    
    HOST ='127.0.0.1'
    PORT = 21567
    BUFSIZE = 1024
    ADDR = (HOST,PORT)
    
    udpclient = socket(AF_INET,SOCK_DGRAM)
    
    while True:
        data = input('>')
        if not data:
            break
        udpclient.sendto(data.encode(),ADDR)
        data,ADDR = udpclient.recvfrom(BUFSIZE)
        if not data:
            break
        print(data)
    udpclient.close()
    

      

  • 相关阅读:
    pandas isin 和not in
    游戏开发需要学什么?
    打开页面,数字会自增的效果怎么弄?
    jq 导航栏点击添加/删除类(a标签跳转页面)
    bootstrap+jq分页
    2020/12/18
    2020/12/17
    2020/12/16
    2020/12/15
    2020/12/14
  • 原文地址:https://www.cnblogs.com/HCT118/p/5876765.html
Copyright © 2020-2023  润新知