#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()
运行结果:
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)