// An highlighted block
#1 tcp连接方式
#服务器端
import socket
sk=socket.socket()
sk.bind(('127.0.0.1',9001)) #申请操作系统资源
sk.listen()
while True:
conn, addr = sk.accept() #conn里存储的是一个客户端和server端连接信息
while True:
st= input('<<<')
conn.send(st.encode('utf-8'))
if (st.upper() == 'Q'):
break
msg= conn.recv(1024).decode()
print(msg)
conn.close() #挥手断开连接
sk.close() #释放操作系统资源
#客户端
import socket
sk=socket.socket()
sk.connect(('127.0.0.1',9001))
while True:
msg = sk.recv(1024).decode()
if msg.upper()=='Q':
break
print(msg)
st= input('>>>')
sk.send(st.encode())
sk.close()
#2 udp 连接方式
#服务器端
import socket
sk=socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',9002))
msg,addr=sk.recvfrom(1024)
print(msg)
sk.sendto(b'nihao',addr)
#客户端
import socket
sk=socket.socket(type=socket.SOCK_DGRAM)
sever=('127.0.0.1',9002)
sk.sendto(b'nihaofuwuduan',sever)
msg=sk.recv(1024)
print(msg)
python socket简单的连接
最新推荐文章于 2024-07-12 22:25:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)