欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python socket TCP服务器/客户端 + UDP 发送端/接收端

程序员文章站 2022-04-24 14:13:41
...
'''
socket 
'''
import socket
def tcp_server():
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind(('0.0.0.0',9999))
    s.listen()
    print(socket.gethostbyname(socket.gethostname()),9999,'server starting ......')
    while True:
        try:
            client,addr = s.accept()
            recv = client.recv(1024).decode()
            print(addr[0],addr[1],'>>',recv)
            client.send(recv.encode())
        except:
            print(addr[0],addr[1],'>>','say goodby')

def tcp_client():
    while True:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((socket.gethostbyname(socket.gethostname()),9999))
        text = input('send:').encode()
        s.send(text)
        response = s.recv(1024).decode()
        print(response)
        s.close()

def udp_recver():
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    ip = socket.gethostbyname(socket.gethostname())
    port = int(input('\ninput your recver port please:'))
    s.bind((ip,port))
    print(ip,port,'listening......')    
    data,addr = s.recvfrom(1024)
    print(addr,':',data.decode())
    s.sendto(data,addr)

def udp_sender():
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    ip = input('input target ip please:')
    port = int(input('input target port please:'))
    text = input('send:').encode()
    s.sendto(text,(ip,port))
    data,addr = s.recvfrom(1024)
    print(data.decode())

def select_type():
    return tcp_client()

if __name__ == '__main__':
    select_type()