最简单的网络通讯
server端:
import socket
sk = socket.socket() # 创建一个server端的对象
sk.bind(('127.0.0.1',9001)) # 给server端绑定一个地址
sk.listen() # 开始监听(可以接收)客户端给我的连接了
conn,addr = sk.accept() # 建立连接 conn是连接
conn.send(b'hello')
msg = conn.recv(1024)
print(msg)
conn.close() # 关闭连接
sk.close()
client端:
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',9001))
msg = sk.recv(1024)
print(msg)
sk.send(b'byebye')
sk.close()
tcp 和多个客户端通讯
#server端
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8008))
sk.listen()
while True:
conn, addr = sk.accept()
print('conn',conn)
while True:
g = input('请输入:')
conn.send(g.encode('utf-8'))
if g.upper() == 'Q':
break
msg = conn.recv(1024).decode('utf-8')
print(msg)
conn.close()
sk.close()
#-------------------------
#Client端
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8008))
while True:
msg = sk.recv(1024).decode('utf-8')
if msg.upper() == 'Q':break
print(msg)
g = input('>>>')
sk.send(g.encode('utf-8'))
if g.upper() == 'Q':break
sk.close()
UDP协议通讯
#udp例子
#server端------------------
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8001))
while True:
msg,addr = sk.recvfrom(1024)
print(msg.decode('utf-8'))
msg_send = input('>>>')
if msg_send.upper() == 'Q':break
sk.sendto(msg_send.encode('utf-8'),addr)
#client端 ------------------
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
server = ('127.0.0.1',8001)
while True:
msg = input('>>>')
if msg.upper() == 'Q':break
sk.sendto(msg.encode('utf-8'),server)
msg2 = sk.recv(1024).decode('utf-8')
if msg2.upper() =='Q':break
print(msg2)