网络编程udp


网络编程udp-socket

1.socketServer:启动程序,通过网络调试助手向指定IP发送信息,在后台打印出发送人信息和发送内容
from socket import *

def main():
    udpSocket = socket(AF_INET, SOCK_DGRAM)

    udpSocket.bind(("", 6789))

    #收,打印
    while True:
        recvInfor = udpSocket.recvfrom(1024)
        print("[%s]:%s"%(str(recvInfor[1]), recvInfor[0].decode("gb2312")))

if __name__ == "__main__":
    main()
2.socketClite:多进程启动,收发信息互不影响,后台打印聊天内容
from socket import *
from threading import Thread


def recv():
    while True:
        info = udpsocket.recvfrom(1024)
        print('\>>>发送人:%s , 内容:%s' % (str(info[1]), info[0].decode('gb2312')))

def send():
    while True:
        sendinfo = input('<<< ')
        udpsocket.sendto(sendinfo.encode('gb2312'), (TargethostIP, TargethostPort))

def main():
    global udpsocket
    global TargethostIP
    global TargethostPort

    udpsocket = socket(AF_INET, SOCK_DGRAM)
    udpsocket.bind(('', 5678))
    TargethostIP = input('对方的ip:')
    TargethostPort = int(input('对方的port:'))

    tr = Thread(target=recv)
    ts = Thread(target=send)
    tr.start()
    ts.start()
    tr.join()
    ts.join()


if __name__ == '__main__':
    main()
3.socketClite:多进程启动,收发信息互不影响,后台打印聊天内容并记录到log日志
import time
from socket import *
from threading import Thread
import socket

def get_ip(ip='192.168.138.39', port=6500):
    S_ip = ip
    S_port = port
    return S_ip, S_port

def send():
    while 1:
        sendnr = input('请输入发送内容:')
        sk.sendto(sendnr.encode('gbk'), ip_port)
        flag = True
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        with open('udp.log', 'a') as f:
            f.write('\n' + now_time + ' 发送内容:' + sendnr)

def recv():
    while 1:
        recvnr = sk.recvfrom(1024)
        nr = recvnr[0].decode('gbk')
        ip_port = recvnr[1]
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        info = '\n%s 接受内容: nr: %s, ip and port: %s'% (now_time, nr, ip_port)
        print(info)
        flag = False
        with open('udp.log', 'a') as f:
            f.write(info)



def main():
    global sk
    global ip_port
    sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sk.bind(('', 5678))
    sip = input('对方ip')
    if len(sip) > 0:
        sport = int(input('对方port'))
        ip_port = get_ip(sip, sport)
        with open('udp.log', 'a') as f:
            f.write('\n' + str(ip_port))
    else:
        ip_port = get_ip()
        with open('udp.log', 'a') as f:
            f.write('\n' + str(ip_port))

    ts = Thread(target=send)
    tr = Thread(target=recv)
    ts.start()
    tr.start()
    ts.join()
    tr.join()


if __name__ == '__main__':
    main()


你可能感兴趣的:(Python3)