需求分析:对讲机程序,主要实现使用软件的双方之间一对一通信功能
服务端 TCP_Serve
import socket
from datetime import datetime
print("初始化服务器")
HOST = ''
PORT = 8888
ADDRESS = (HOST, PORT)
BUFFER = 1024
print("创建服务器主机套接字对象")
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("绑定主机")
tcp_socket.bind(ADDRESS)
print("启动服务器")
tcp_socket.listen(128)
while True:
print("等待客户端连接=======")
client_socket, client_addr = tcp_socket.accept()
print("客户端{}连接成功".format(client_addr))
info = "你好,欢迎访问服务器!!"
client_socket.send(info.encode("utf-8"))
while True:
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
msg = client_socket.recv(BUFFER)
try:
print(now_time, "client客户端1:{}".format(msg.decode("utf-8")))
except:
print(now_time, "client客户端2:{}".format(msg.decode("gbk")))
info = input("请输入内容:")
client_socket.send(info.encode("utf-8"))
print("发送成功")
if msg == b'bye':
print("客户端退出")
client_socket.close()
break
tcp_socket.close()客户端 TCP_Client
import socket
from datetime import datetime
print("连接目标服务器")
HOST = "192.168.11.195"
PORT = 8888
ADDRESS = (HOST, PORT)
BUFFER = 1024
print("创建服务器主机套接字对象")
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("连接指定服务器")
tcp_client.connect(ADDRESS)
while True:
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
info = tcp_client.recv(BUFFER)
print(now_time, "server服务端:", info.decode("utf-8"))
msg = input("输入内容:")
tcp_client.send(msg.encode("utf-8"))
print("发送成功")
if msg.lower() == "bye":
tcp_client.close()
print("客户端退出。。。")
break
随时随地看视频