python 網絡編程-TCP/UDP

摘抄自:廖雪峯的官方網站:http://www.liaoxuefeng.com/服務器

TCP客戶端和服務器端代碼:socket


 

#coding=utf-8
#客戶端程序TCP 鏈接

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect(('127.0.0.1',9999))

print(s.recv(1024))

for data in ['Michael','Tracy','Sarah']:
    s.send(data.encode())
    print(s.recv(1024))

s.send(b'exit')
#coding=utf-8
#TCP服務器端程序
import socket
import time
import threading



def tcplink(sock,addr):
    print("accept new connection from %s:%s..." % addr)
    sock.send("Welcom!".encode())
    while True:
        data=sock.recv(1024)
        time.sleep(1)
        if data=='exit' or not data:
            break
        sock.send("hello: ".encode()+data)
    sock.close()
    print("Connection from %s:%s closed." % addr)
    
    
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 建立一個基於ipv4 的TCP協議的socket

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

Waiting for connection......
accept new connection from 127.0.0.1:60218...
Connection from 127.0.0.1:60218 closed.
b'Welcom!'
b'hello: Michael'
b'hello: Tracy'
b'hello: Sarah'

 

 

UDP客戶端和服務器端代碼:網站


 

#coding=utf-8
#UDP 客戶端代碼

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

for data in ["chenshan","yuanhui","chendianqiang"]:
    s.sendto(data.encode(),('127.0.0.1',9999))
    print(s.recv(1024))
    
s.close()
#coding=utf-8
#UDP 協議服務器代碼
import socket

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind(('127.0.0.1',9999))
print("Bind UDP on prot:9999")

while True:
    data,addr=s.recvfrom(1024)
    print("Receive from %s:%s"% addr)
    s.sendto("Hello ".encode()+data,addr)

運行結果:ui

Bind UDP on prot:9999
b'Hello chenshan'
b'Hello yuanhui'
b'Hello chendianqiang'
相關文章
相關標籤/搜索