TCP服务器通讯:
import socket sk=socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen() print("正在开启监听模式") client,comment=sk.accept() print(client,comment) while 1: msg_c=client.recv(1024) print(msg_c.decode('utf-8')) msg_s=input('>>>>>>>') client.send(msg_s.encode('utf-8')) client.close() sk.close()
Tcp客户端通讯:
import socket sk=socket.socket() sk.connect(('127.0.0.1',8080)) while 1: msg_c=input('>>>>>>') sk.send(msg_c.encode('utf-8')) msg_s=sk.recv(1024) print(msg_s.decode('utf-8')) sk.close()
UDP服务器:
import socket sk=socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',9090)) while 1: msg_c,add=sk.recvfrom(1024) print(msg_c.decode('utf-8')) msg_s=input('>>>') sk.sendto(msg_s.encode('utf-8'),add) sk.close()
UDP客户端:
import socket sk=socket.socket(type=socket.SOCK_DGRAM) while 1: msg_c=input('>>>') sk.sendto(msg_c.encode('utf-8'),('127.0.0.1',9090)) msg_r,add=sk.recvfrom(1024) print(msg_r.decode('utf-8')) sk.close()
扩展方法UDP不转utf-8格式:
class my_socket(socket.socket): def __init__(self,encoding='utf-8'): self.encoding=encoding super(my_socket, self).__init__(type=socket.SOCK_DGRAM) def send(self,msg,addr): return self.sendto(msg.encode(self.encoding),addr) def receive(self,num): msg,addr=self.recvfrom(num) return msg.decode(self.encoding),addr
重写socket的一个子类,通过子类调用父类socket方法
udp服务器:
from My_Socket import my_socket sk = my_socket() sk.bind(('127.0.0.1', 8080)) while 1: msg, addr = sk.receive(1024) print(msg) msg_s = input('>>>>>>') sk.send(msg_s, addr) sk.close()
UDP客户端:
from My_Socket import my_socket # sk = my_socket() while 1: msg_c=input('>>>>>') sk.send(msg_c,('127.0.0.1',8080)) msg,addr=sk.receive(1024) print(msg) sk.close()
扩展方法TCP不转utf-8格式:
class my_sockettcp(socket.socket): def __init__(self,encoding="utf-8"): self.encoding=encoding super(my_sockettcp, self).__init__(type=socket.SOCK_STREAM) def Tcpsend(self,cli,msg): return cli.send(msg.encode(self.encoding)) def Tcpreceive(self,cli,num): msg=cli.recv(num) return msg.decode(self.encoding)
TCP服务器:
from My_Socket import my_sockettcp sk=my_sockettcp() sk.bind(('192.168.12.16',18080)) sk.listen() print("正在监听") cli,addr=sk.accept() print(cli) while 1: msg=sk.Tcpreceive(cli,1024) print(msg) msg_s=input('>>>>>') sk.Tcpsend(cli,msg) cli.close() sk.close()
Tcp客户端:
from My_Socket import my_sockettcp sk=my_sockettcp() sk.connect(('192.168.12.16',18080)) while 1: msg=input('>>>>>') sk.Tcpsend(sk,msg) msg_s=sk.Tcpreceive(sk,1024) print(msg_s) sk.close()
Pycharm输出带颜色字体:
33[字体颜色;背景颜色m 数据 33[0m
TCP协议的三次握手与四次挥手:
tcp三次握手: 一定是client先发起请求
a 客户端发起请求连接服务器
b 服务器返回 : 接收到请求,并要求连接客户端
c 客户端回复 : 可以连接
四次挥手: 谁先发起断开连接的请求都可以
a 客户端发起断开连接的请求:
意思是: 我想和你断开连接,我没有数据要继续发送了,但是如果你有数据需要发送,我可以继续接收
b 服务器回复 : 我接收到你的请求了
c 服务器发送 : 我已经准备好断开连接了
d 客户端回复 : 收到你的信息,断开连接