缓冲区英文Buffer,因此缓冲区大小定义为BUF_SIZE
TCP服务端:
import socket
ip_port = ('127.0.0.1', 9000)
BUF_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ip_port)
s.listen(5)
while True:
conn, addr = s.accept()
print('接收到来自%s的电话' % addr[0])
while True:
try:
msg = conn.recv(BUF_SIZE)
print(msg, type(msg))
if len(msg) == 0:
break
conn.send(msg.upper())
except Exception:
break
conn.close()
s.close()
TCP客户端:
import socket
ip_port = ('127.0.0.1', 9000)
BUF_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ip_port)
while True:
msg = input('>>:').strip()
if len(msg) == 0:
continue
s.send(msg.encode('utf-8'))
feedbacks = s.recv(BUF_SIZE)
print(feedbacks.decode('utf-8'))
s.close()
UDP服务端:
import socket
ip_port = ('127.0.0.1', 9000)
BUF_SIZE = 1024
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
u.bind(ip_port)
while True:
msg, addr = u.recvfrom(BUF_SIZE)
print(msg, addr)
u.sendto(msg.upper(), addr)
u.close()
UDP客户端:
import socket
ip_port = ('127.0.0.1', 9000)
BUF_SIZE = 1024
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
msg = input('>>:').strip()
if not msg:
continue
u.sendto(msg.encode('utf-8'), ip_port)
back_msg, addr = u.recvfrom(BUF_SIZE)
print(back_msg.decode('utf-8'), addr)
u.close()



