python socket 编程
TCP IPv4
# server.py
import socket
import threading
import time
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',9999))
s.listen(5)
print('Waiting connection...')
def tcp_link(sock,addr):
print('Accept new data info from %s:%s...' %addr)
# 首先向 客户端发送 hello 消息
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(('Hello %s' %data.decode('utf-8')).encode('utf-8'))
sock.close()
print('connection %s:%s closed...' %addr)
while True:
# 等待客户端发送消息
sock, addr = s.accept()
# 为每一个客户端都单独开启一个线程
t = threading.Thread(target=tcp_link,args=(sock,addr))
t.start()
# custom.py
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'))
for data in [b'a',b'b',b'c']:
s.send(data)
print('received data %s' %s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()
UDP IPV4
# server2.py
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',9998))
while True:
data, addr = s.recvfrom(1024)
print('from %s:%s...' % addr)
print(data.decode('utf-8'))
s.sendto(b'Hello %s' %data,addr)
# custom2.py
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
for data in [b'a',b'b',b'c']:
s.sendto(data,('127.0.0.1',9998))
receive_data = s.recv(1024)
print(receive_data.decode('utf-8'))
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。