1 # tcp
2 # server
3 import socket
4 sk = socket.socket() # 买手机 # 创建一个socket对象
5 sk.bind(("127.0.0.1",8081)) # 给server端绑定一个ip和端口
6 sk.listen() # 括号里写数字,代表着允许几个人连接我
7 while True:
8 conn,addr = sk.accept() # 传过来的一定是一个元祖
9 # 这是获取到一个客户端的连接,已经完成了三次握手建立一个连接。
10 # 这时会阻塞
11 while True:
12 msg = conn.recv(1024).decode("utf-8") # 阻塞 会一直停在这里
13 # 直到收到一个客户端发来的消息
14 print(msg)
15 if msg == "bye":
16 break
17 info = input(">>>")
18 if info == "bye":
19 conn.send(b"bye")
20 break
21 conn.send(info.encode("utf-8")) # 发信息
22 conn.close() # 关闭连接
23 sk.close() # 关闭socket对象,如果不关闭,还能继续接收
24
25 # client
26
27 import socket
28 sk = socket.socket()
29 sk.connect(("127.0.0.1",8081))
30 while True:
31 msg = input(">>>")
32 if msg == "bye":
33 sk.send(b"bye")
34 break
35 sk.send(msg.encode("utf-8"))
36 ret = sk.recv(1024).decode("utf-8")
37 if ret == "bye":
38 break
39 print(ret)
40 sk.close()
41
# client2
# import socket
# sk = socket.socket()
# sk.connect(("127.0.0.1",8081))
# while True:
# msg = input("client2:>>>")
# if msg == "bye":
# sk.send(b"bye")
# break
# sk.send(("client2:" + msg).encode("utf-8"))
# ret = sk.recv(1024).decode("utf-8")
# if ret == "bye":
# break
# print(ret)
# sk.close()
42
43
44 # udp
45 # import socket
46 # sk = socket.socket(type=socket.SOCK_DGRAM)
47 # sk.bind(("127.0.0.1",8081))
48 #
49 # msg,addr = sk.recvfrom(1024)
50 # print(msg.decode("utf-8"))
51 # sk.sendto(b"bye",addr)
52 # sk.close()
53
54
55 # udp的server 不需要进行监听,也不需要建立连接
56 # 在启动服务之后只能被动的等待客户端发送消息过来
57 # 客户端发送消息的同时还会 自带地址信息
58 # 消息回复的时候 不仅需要发送消息,还需要把对方的地址在发送回去
59
60 # client
61
62 # import socket
63 # sk = socket.socket(type=socket.SOCK_DGRAM)
64 # ip_port = ("127.0.0.1",8081)
65 #
66 # sk.sendto(b"hello",ip_port)
67 # ret,addr = sk.recvfrom(1024) # 没有链接,所以收发时都要带着地址
68 # print(ret.decode("utf-8"))
69 #
70 # sk.close()
71
72
73 # udp
74
75 import socket
76 sk = socket.socket(type=socket.SOCK_DGRAM)
77 sk.bind(("127.0.0.1",8080))
78 while True:
79 msg,addr = sk.recvfrom(1024)
80 print(addr)
81 print(msg.decode("utf-8"))
82 info = input(">>>").encode("utf-8")
83 sk.sendto(info,addr)
84 sk.close()
85
86
87 import socket
88 sk = socket.socket(type=socket.SOCK_DGRAM)
89 ip_port = ("127.0.0.1",8080)
90 while True:
91 info = input("二哥:")
92 info = ("\033[32m来自二哥的消息:%s\033[0m"%info).encode("utf-8")
93 sk.sendto(info,ip_port)
94 msg,addr = sk.recvfrom(1024)
95 print(msg.decode("utf-8"))
96 sk.close()
# client2
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ("127.0.0.1",8080)
while True:
info = input("tiger:")
info = ("\033[34m来自tiger的消息:%s\033[0m"%info).encode("utf-8")
sk.sendto(info,ip_port)
msg,addr = sk.recvfrom(1024)
print(msg.decode("utf-8"))
sk.close()
# 注:本文是根据老男孩课程内容整理而成的,本文仅供个人笔记使用,如果有侵犯,请联系我,我立即撤销。