tcp协议的聊天 --- 编码
udp协议的聊天 --- 编码
基于udp协议的时间同步机制 --- 编码(pycharm控制台输出带颜色)
import socket
sk = socket.socket(family = socket.AF_INET,type = socket.SOCK_STREAM)
参数1 family : 套接字类型
参数2 type : 通信协议类型 tcp协议 , udp协议
tcp协议 : SOCK_STREAM
udp协议 : SOCK_DGRAM
family = socket.AF_INET 采用网络形式通信的套接字
family = socket.AF_UNIX 采用文件类型通信的套接字
TCP客户端:
from socket import socket
sk = socket()
sk.connect(("服务器IP地址",端口号))
while 1:
a = input("<<<")
sk.send(a.encode("utf-8"))
if a == "q":
break
ret = sk.recv(1024)
print(ret.decode("utf-8")
if ret.decode("utf-8") == "q":
break
sk.close()
TCP服务器端:
from socket import socket
sk = socket()
sk.bind(("127.0.0.1",9090))
sk.listen()
while 1:
conn,addr = sk.accept()
while 1:
ret = conn.recv(1024)
print(ret.decode("utf-8")
if ret.decode("utf-8") == "q":
break
a = input("<<<")
conn.send(a.encode("utf-8"))
if a == "q":
break
conn.close()
sk.close()
UDP协议客户端:
import socket
sk = socket.socket(type = socket.SOCK_DFRAM)
while 1:
a = input("<<<")
sk.sendto(("name" + ":" + a).encode("utf-8"),("127.0.0.1",9090))
if a == "q":
break
conn,addr = sk.recvfrom(1024)
print(" 33[0;31;43m%s 33[0m"%conn.decode("utf-8"))
if conn.decode("utf-8") == "q":
break
sk.close
UDP协议 服务器端:
import socket
sk = socket.socket(type = socket.SOCK_DGRAM)
sk.bind(("127.0.0.1",9090))
while 1:
conn,addr = sk.recvfrom(1024)
print(" 33[0;31m%s 33[0m"%conn.decode("utf-8"))
if conn.decode("utf-8") == "q":
continue #这里不用break,是因为还有别的客户连接.
a = input("<<<")
sk.sendto(a.encode("utf-8"),addr)
if a == "q":
break
sk.close()
UDP协议时间同步机制 (客户端)
import socket
import time
sk = socket.socket(type = socket.SOCK_DGRAM)
while 1:
sk.sendto("%Y-%m-%d %H:%M:%S".encode("utf-8"),("127.0.0.1",9090))
conn,addr = sk.recvfrom(1024)
print(conn.decode("utf-8")
time.sleep(2)
sk.close()
UDP协议 时间同步机制(服务器端)
import socket
import time
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(("127.0.0.1",9090))
while 1:
conn,addr = sk.recvfrom(1024)
ret = time.strftime(conn.decode("utf-8"))
sk.sendto(ret.encode("utf-8",addr)
sk.close()
1.把以上的代码敲会
2.把tcp协议的编码完善 udp协议的代码加上带颜色的输出