B/S架构和C/S架构的介绍与分析

说在前面的话:其实不想写的,写了估计也没人看,毕竟现在愿意学这个的人少了,但是转念一想,万一有人需要呢?写毕业论文或者综述论文的时候可以看看。

一、B/S架构

1.原理介绍

B/S 架构即浏览器 / 服务器架构(Browser/Server Architecture)。它是随着 Internet 技术的兴起,对传统 C/S(客户端 / 服务器)架构的一种发展与改进。在 B/S 架构下,用户通过浏览器(如谷歌浏览器、火狐浏览器、IE 浏览器等)作为客户端来访问应用程序。服务器端通常部署在数据中心或云端,负责处理业务逻辑、存储数据等核心任务。

当用户在浏览器中输入网址(URL)访问一个基于 B/S 架构的应用程序时,浏览器会向服务器发送 HTTP(HyperText Transfer Protocol,超文本传输协议)请求。服务器接收到请求后,会根据请求的内容和 URL 路径,调用相应的应用程序逻辑。这可能涉及到与数据库的交互,例如查询数据、插入新记录等。服务器处理完请求后,会生成一个 HTML(HyperText Markup Language,超文本标记语言)页面,该页面包含了用户需要查看的信息以及一些客户端脚本(如 JavaScript),然后通过 HTTP 响应将这个页面发送回浏览器。浏览器接收到响应后,会解析 HTML 内容并按照其定义的结构和样式呈现网页给用户。如果用户在页面上进行交互操作,如点击按钮、提交表单等,浏览器会再次向服务器发送新的 HTTP 请求,触发服务器端进一步的处理。

2.代码分析

2.1 服务器代码

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# 存储用户数据的简单字典(实际项目中通常使用数据库)
users = {}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 简单的用户注册逻辑
        if username and password and username not in users:
            users[username] = password
            return redirect(url_for('login'))
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 简单的用户登录逻辑
        if username in users and users[username] == password:
            return redirect(url_for('welcome', username=username))
    return render_template('login.html')

@app.route('/welcome/<username>')
def welcome(username):
    return render_template('welcome.html', username=username)

if __name__ == '__main__':
    app.run(debug=True)

要跑这个代码,需要先安装Flask框架,并将上述服务器端代码保存为app.py,前端页面保存在与app.py同目录下的templates文件夹中(需要自己创建该文件夹)。

2.2 前端代码1

这是index.html,是主页前端。

<!DOCTYPE html>
<html>
<head>
    <title>主页</title>
</head>
<body>
    <h1>欢迎来到B/S架构示例</h1>
    <p>请<a href="{{ url_for('register') }}">注册</a>或<a href="{{ url_for('login') }}">登录</a></p>
</body>
</html>

2.2 前端代码2

这是register.html(注册页面)

<!DOCTYPE html>
<html>
<head>
    <title>注册</title>
</head>
<body>
    <h1>用户注册</h1>
    <form method="post">
        <label for="username">用户名:</label>
        <input type="text" name="username" id="username" required><br>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password" required><br>
        <button type="submit">注册</button>
    </form>
    <p>已有账号?<a href="{{ url_for('login') }}">登录</a></p>
</body>
</html>

2.3 前端代码3

不想写了,写了也没人看,登录界面如下

<!DOCTYPE html>
<html>
<head>
    <title>登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form method="post">
        <label for="username">用户名:</label>
        <input type="text" name="username" id="username" required><br>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password" required><br>
        <button type="submit">登录</button>
    </form>
    <p>没有账号?<a href="{{ url_for('register') }}">注册</a></p>
</body>
</html>

2.4 前端代码4

最后的一部分,欢迎界面

<!DOCTYPE html>
<html>
<head>
    <title>欢迎</title>
</head>
<body>
    <h1>欢迎,{{ username }}</h1>
    <p>您已成功登录系统。</p>
</body>
</html>

二、C/S架构

1.原理介绍

C/S架构即客户端/服务器架构(Client/Server Architecture),是由客户端和服务器端组成的分布式计算模式。在这个架构中,客户端负责与用户交互,提供友好的用户界面,而服务器端则主要处理数据存储、业务逻辑等核心任务。

当用户在客户端上发起操作时,客户端应用程序会向服务器发送请求。服务器接收到请求后,会根据客户端的具体需求,进行相应的数据处理和业务逻辑计算,然后将处理结果返回给客户端。例如,在一个基于C/S架构的银行系统中,当用户在客户端上查询账户余额时,客户端应用程序会将查询请求发送到服务器,服务器则会查询数据库,找到用户的账户信息,并将余额数据返回给客户端,最后由客户端将结果显示给用户。

C/S架构的客户端和服务器端之间通过网络进行通信,它们之间遵循一定的通信协议,如TCP/IP协议等。这种架构的优势在于良好的交互性和响应速度,因为客户端可以预加载必要的程序和数据,减少与服务器的数据传输频率,能够快速响应用户的操作。同时,服务器端可以集中管理数据和业务逻辑,保证数据的一致性和安全性,便于进行数据的维护和升级。

2.代码分析

2.1 服务器端代码

服务器端 :创建一个套接字对象,绑定到指定的地址和端口,并开始监听连接。当有客户端连接时,接受连接并创建一个新线程来处理该客户端的请求。在处理客户端请求的线程中,服务器不断接收客户端发送的消息,并将响应消息发送回客户端。

import socket
import threading

# 定义服务器地址和端口
HOST = '127.0.0.1'
PORT = 65432

# 创建服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)  # 最大连接数为5

print(f"服务器已启动,监听地址:{HOST}:{PORT}")

def handle_client(client_socket):
    """处理客户端请求的函数"""
    while True:
        try:
            # 接收客户端发送的消息
            request = client_socket.recv(1024).decode('utf-8')
            if not request:
                break
            print(f"收到客户端消息:{request}")
            
            # 发送响应消息给客户端
            response = f"服务器已收到你的消息:{request}"
            client_socket.send(response.encode('utf-8'))
            
        except ConnectionResetError:
            # 客户端断开连接
            print("客户端已断开连接")
            break
    
    client_socket.close()

while True:
    # 接受客户端连接
    client_socket, client_address = server_socket.accept()
    print(f"客户端已连接:{client_address}")
    
    # 为每个客户端创建一个线程
    client_thread = threading.Thread(target=handle_client, args=(client_socket,))
    client_thread.start()

2.2 客户端代码

客户端 :创建一个套接字对象并连接到服务器的地址和端口。然后进入循环,等待用户输入消息并发送给服务器,同时接收服务器的响应并显示出来。如果用户输入 “exit”,客户端将退出并关闭套接字。

import socket

# 定义服务器地址和端口
HOST = '127.0.0.1'
PORT = 65432

# 创建客户端套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

while True:
    # 输入要发送的消息
    message = input("请输入要发送的消息(输入'exit'退出):")
    
    # 发送消息到服务器
    client_socket.send(message.encode('utf-8'))
    
    # 如果输入'exit',则退出客户端
    if message.lower() == 'exit':
        break
    
    # 接收服务器的响应
    response = client_socket.recv(1024).decode('utf-8')
    print(f"服务器响应:{response}")

# 关闭客户端套接字
client_socket.close()

三、实际项目展示

1. 简单的网络聊天应用(C/S架构)

C/S架构的前端:通常是一个独立的客户端应用程序,安装在用户的本地设备上。这个应用程序通常是使用编程语言如C++、Java、C#等编写,并且需要根据不同的操作系统(如Windows、macOS、Linux)进行专门的开发。它与后端服务器进行通信,通过网络发送请求并接收响应。客户端应用程序可以直接访问本地资源,提供更丰富的用户界面和交互功能。例如,在一个C/S架构的办公软件中,前端客户端可以提供复杂的文档编辑功能和本地数据存储。

服务器端代码如下(server.py)

import socket
import threading

# 定义服务器地址和端口
HOST = '127.0.0.1'
PORT = 65432

# 创建服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)  # 最大连接数为5

print(f"服务器已启动,监听地址:{HOST}:{PORT}")

clients = []  # 用于存储连接的客户端套接字

def handle_client(client_socket):
    """处理客户端消息的函数"""
    while True:
        try:
            # 接收客户端发送的消息
            message = client_socket.recv(1024).decode('utf-8')
            if not message:
                break
            print(f"收到客户端消息:{message}")
            
            # 将消息广播给所有其他客户端
            for client in clients:
                if client != client_socket:
                    client.send(message.encode('utf-8'))
            
        except ConnectionResetError:
            # 客户端断开连接
            print("客户端已断开连接")
            break
    
    # 从客户端列表中移除断开的客户端
    clients.remove(client_socket)
    client_socket.close()

while True:
    # 接受客户端连接
    client_socket, client_address = server_socket.accept()
    print(f"客户端已连接:{client_address}")
    clients.append(client_socket)
    
    # 为每个客户端创建一个线程
    client_thread = threading.Thread(target=handle_client, args=(client_socket,))
    client_thread.start()

客户端代码如下(client.py)

import socket
import threading

# 定义服务器地址和端口
HOST = '127.0.0.1'
PORT = 65432

# 创建客户端套接字并连接到服务器
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

def receive_messages():
    """接收服务器发送的消息"""
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            print(message)
        except ConnectionResetError:
            print("与服务器的连接已断开")
            break

# 创建接收消息的线程
receive_thread = threading.Thread(target=receive_messages)
receive_thread.start()

# 发送消息给服务器
while True:
    message = input()
    client_socket.send(message.encode('utf-8'))

 2.简单的网络聊天应用(B/S架构)

B/S架构的前端:主要是指浏览器端,用户通过浏览器访问Web应用程序。前端开发使用HTML、CSS和JavaScript等Web技术来创建用户界面和实现交互逻辑。浏览器作为客户端,通过HTTP协议与服务器进行通信。前端代码在浏览器中运行,与服务器端进行数据交互,通常通过AJAX、Fetch API等方式获取和提交数据。例如,在一个B/S架构的在线购物网站中,前端页面使用HTML定义结构,CSS进行样式设计,JavaScript实现交互效果,如商品筛选、购物车功能等。

服务器端代码(app.py)
from flask import Flask, render_template
from flask_socketio import SocketIO, send, join_room, leave_room

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('message')
def handle_message(message):
    print(f"收到消息:{message}")
    send(message, broadcast=True)

if __name__ == '__main__':
    socketio.run(app, debug=True)
前端页面(templates/index.html)
<!DOCTYPE html>
<html>
<head>
    <title>简单Web聊天应用</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #chat-container {
            width: 80%;
            margin: 0 auto;
            font-family: Arial, sans-serif;
        }
        #messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
        }
        #message-input {
            width: 70%;
            padding: 8px;
            margin-right: 5px;
        }
        #send-button {
            padding: 8px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="chat-container">
        <h1>简单Web聊天应用</h1>
        <div id="messages"></div>
        <input type="text" id="message-input" placeholder="输入消息...">
        <button id="send-button">发送</button>
    </div>

    <script>
        $(document).ready(function() {
            var socket = io();

            $('#send-button').click(function() {
                var message = $('#message-input').val();
                if (message.trim() !== '') {
                    socket.emit('message', message);
                    $('#messages').append('<div><strong>我:</strong>' + message + '</div>');
                    $('#message-input').val('');
                }
            });

            socket.on('message', function(message) {
                $('#messages').append('<div>' + message + '</div>');
            });

            // 按下回车键发送消息
            $('#message-input').keypress(function(e) {
                if (e.which === 13) {
                    $('#send-button').click();
                }
            });
        });
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摆烂仙君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值