Python3 TCP UDP 编程

参考廖雪峰的Python教程,实现Python3 TCP UDP 编程

TCP server

#!/usr/bin/python3
# coding: utf-8

import socket 
import threading 
import time 

def tcplink(sock, addr):
    print("accept connect from %s:%s" %(addr))
    sock.send(b"welcome")
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode("utf-8") == "exit":
            break 
        sock.send(b"hello, %s" %(data))

    sock.close()
    print("connect from %s:%s closed" %(addr))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 9999))
s.listen(5)
print("waiting for connection")

while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()

TCP client

#!/usr/bin/python3
# coding: utf-8

import socket 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9999))

print(s.recv(1024).decode("utf-8"))
s.send(b"python")
print(s.recv(1024).decode("utf-8"))
s.send(b"exit")
s.close()

UDP server

#!/usr/bin/python3
# coding: utf-8

import socket 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("127.0.0.1", 9999))

while True:
    print("waiting for udp connection")
    data, addr = s.recvfrom(1024)
    print("receive from %s:%s" %(addr))
    s.sendto(b"welcome", addr)
    s.sendto(b"hello, %s" %(data), addr)
    s.sendto(b"exit", addr)

UDP client

#!/usr/bin/python3
# coding: utf-8

import socket 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b"python", ("127.0.0.1", 9999))

while True:
    data, addr = s.recvfrom(1024)
    if data.decode("utf-8") == "exit":
        break 
    print(data.decode("utf-8"))

s.close()

你可能感兴趣的:(Python)