服务端:
import socket
#1.买手机
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STEAM=>TCP流式协议,
print(phone) #是用来接收链接请求,从而建立链接的
# phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# print(phone)
#2.插手机卡
phone.bind(('127.0.0.1',8080)) #0-65535
#3.开机
phone.listen(5) # 同一时刻最大请求数为5个
print('start....')
#4.等待电话请求
conn,client_addr=phone.accept() #(双向链接的套接字对象,存放客户端ip和端口的小元组)
# print(conn) # conn代表双向链接,用来收发消息
# print(client_addr)
#5.收发消息
data=conn.recv(1024) #1024接收的最大字节数bytes
print('收到客户的数据',data)
conn.send(data.upper())
#6.挂电话链接
conn.close()
#7.关机
phone.close()
客户端:
import socket
#1.买手机
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STEAM=>TCP流式协议,
#2.拨号
phone.connect(('127.0.0.1',8080))
#3.发收消息
phone.send('hello'.encode('utf-8')) # 只能发bytes类型
data=phone.recv(1024)
print('收到服务端的消息: ',data)
#4.挂电话链接
phone.close()
通信循环模板:
服务端:
import socket
iphone = socket.socket()
iphone.bind(('127.0.0.1',5000))
iphone.listen()
while True:
client,addr = iphone.accept()
print(type(client),client,type(addr),addr)
while True:
try:
data = client.recv(1024)
if not data:
client.close()
break
print('收到客户端消息:%s'% data.decode('utf-8'))
client.send(data.upper())
except ConnectionResetError:
print('客户端强行关闭了连接')
client.close()
break
client.close()
iphone.close()
客户端:
import socket
iphone = socket.socket()
iphone.connect(('127.0.0.1',5000))
while True:
msg = input('>>: ').strip()
iphone.send(msg.encode('utf-8'))
data = iphone.recv(1024)
print('收到服务端消息:%s'%data.decode('utf-8'))
iphone.close()
基于UDP的通信循环:
服务端:
import socket
# UDP协议 在创建socket是 只有一个类型不同
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,proto=0)
server.bind(("127.0.0.1",8888))
while True:
data,addr = server.recvfrom(1024) # 阻塞 直到收到数据为止
print("收到来自%s的消息:%s" % (data.decode("utf-8"),addr[0]))
# 返回值为 数据 和 对方ip地址 和端口号
server.sendto(data.upper(),addr)
print(res)
server.close()
# 写一个UDP的多人聊天程序
#
客户端:
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)
while True:
data = input(">>:").encode("utf-8")
client.sendto(data,("127.0.0.1",8888))
d,addr = client.recvfrom(1024)
print(d.decode("utf-8"))
client.close()