一个非常棒的项目!Hacknet 的 IRC 系统真是让人怀念。我将指导你如何使用 Flask 框架搭建一个类似的在线 IRC 系统。我会提供完整的代码,但请注意,这是一个简化版的 IRC,实际的 IRC 协议(RFC 1459)要复杂得多。
免责声明: 本示例代码仅用于教育目的,请不要直接用于生产环境。IRC 协议有许多细节需要考虑(例如,心跳检测、错误处理、安全性等),这个简化版并未涵盖所有内容。
项目结构:
hacknet_irc/
app.py
templates/
base.html
index.html
irc.html
static/
style.css
requirements.txt
config.py
依赖项(requirements.txt):
Flask==2.0.2
Flask-SocketIO==5.1.0
运行 pip install -r requirements.txt 安装依赖。
配置文件(config.py):
# 服务器配置
HOST = '127.0.0.1'
PORT = 5000
DEBUG = True
# IRC 配置
IRC_SERVER_NAME = 'HackNetIRC'
MAX_CLIENTS = 100
MAX_MESSAGE_LENGTH = 400
主应用文件(app.py):
from flask import Flask, render_template, request, session, redirect, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room
import random
import string
import time
from config import HOST, PORT, DEBUG, IRC_SERVER_NAME, MAX_CLIENTS, MAX_MESSAGE_LENGTH
app = Flask(__name__)
app.config['SECRET_KEY'] = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
socketio = SocketIO(app, cors_allowed_origins='*')
# 存储在线用户和频道信息
online_users = {}
channels = {
'general': {'name': 'General', 'topic': 'Welcome to HackNetIRC!', 'users': []},
# 添加更多频道...
}
# 生成随机用户名(模拟 Hacknet 风格)
def generate_username():
adj = ['Dark', 'Zero', 'Nova', 'Specter', 'Phantom']
noun = ['Byte', 'Glitch', 'Pulse', 'Shadow', 'Spectra']
return f"{random.choice(adj)}{random.choice(noun)}{random.randint(100, 999)}"
# 检查用户名是否可用
def is_username_available(username):
return username not in online_users
# 用户连接,分配用户名
@socketio.on('connect')
def handle_connect():
if len(online_users) >= MAX_CLIENTS:
emit('server_message', {'msg': 'Server is full! Try again later.'})
return False
username = generate_username()
while not is_username_available(username):
username = generate_username()
online_users[username] = request.sid
session['username'] = username
emit('connected', {'username': username, 'msg': f'Welcome to {IRC_SERVER_NAME}, {username}!'})
join_room('general') # 默认加入 general 频道
channels['general']['users'].append(username)
emit('server_message', {'msg': f'{username} joined the server.', 'room': 'general'})
emit('user_joined', {'username': username, 'room': 'general'}, room='general')
# 用户断开连接
@socketio.on('disconnect')
def handle_disconnect():
username = session.get('username')
if username:
leave_room('general') # 离开 general 频道
channels['general']['users'].remove(username)
emit('user_left', {'username': username, 'room': 'general'}, room='general')
emit('server_message', {'msg': f'{username} left the server.'}, room='general')
del online_users[username]
# 处理聊天消息
@socketio.on('send_message')
def handle_message(data):
username = session.get('username')
room = data.get('room', 'general')
msg = data['msg'].strip()[:MAX_MESSAGE_LENGTH]
if msg:
emit('new_message', {'username': username, 'msg': msg, 'time': time.strftime('%H:%M:%S')}, room=room)
# 用户切换频道(暂只支持 general,后续可扩展)
@socketio.on('switch_channel')
def handle_switch_channel(data):
new_channel = data.get('channel', 'general')
if new_channel not in channels:
emit('server_message', {'msg': f'Channel {new_channel} does not exist!'})
return
old_channel = 'general' # 目前只支持一个频道,未来扩展
leave_room(old_channel)
channels[old_channel]['users'].remove(session['username'])
join_room(new_channel)
channels[new_channel]['users'].append(session['username'])
emit('user_left', {'username': session['username'], 'room': old_channel}, room=old_channel)
emit('user_joined', {'username': session['username'], 'room': new_channel}, room=new_channel)
emit('channel_joined', {'channel': new_channel, 'topic': channels[new_channel]['topic']})
# 获取在线用户列表
@socketio.on('get_users')
def handle_get_users():
emit('user_list', {'users': list(online_users.keys())})
# 路由:首页(介绍页面)
@app.route('/')
def index():
return render_template('index.html', server_name=IRC_SERVER_NAME)
# 路由:IRC 客户端页面
@app.route('/irc')
def irc():
if 'username' in session:
return redirect(url_for('index')) # 已连接则重定向
return render_template('irc.html', server_name=IRC_SERVER_NAME)
if __name__ == '__main__':
socketio.run(app, host=HOST, port=PORT, debug=DEBUG)
前端模板:
1. templates/base.html (基础模板)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ server_name }} | {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
{% block content %}{% endblock %}
<script>
var socket = io();
</script>
{% block scripts %}{% endblock %}
</body>
</html>
2. templates/index.html (介绍页,引导进入 /irc)
{% extends 'base.html' %}
{% block title %}Welcome{% endblock %}
{% block content %}
<div class="intro">
<h1>Welcome to {{ server_name }}</h1>
<p>A minimalist IRC server inspired by Hacknet.</p>
<a href="{{ url_for('irc') }}" class="btn">Enter IRC</a>
</div>
{% endblock %}
3. templates/irc.html (核心聊天界面)
{% extends 'base.html' %}
{% block title %}IRC Client{% endblock %}
{% block content %}
<div class="irc-container">
<div class="irc-header">
<span id="server-name">{{ server_name }}</span>
<span id="username"></span>
</div>
<div class="channel-bar">
<button class="channel-btn active" data-channel="general">General</button>
<!-- 更多频道按钮后续添加 -->
</div>
<div id="chat-log"></div>
<div class="user-list">
<h4>Online Users (<span id="user-count">0</span>)</h4>
<ul id="online-users"></ul>
</div>
<div class="input-area">
<input type="text" id="message-input" placeholder="Type your message..." autocomplete="off">
<button id="send-btn">Send</button>
</div>
<div id="status-bar"></div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(document).ready(function() {
var username = null;
var currentChannel = 'general';
// 监听连接成功
socket.on('connected', function(data) {
username = data.username;
$('#username').text(' | ' + username);
$('#status-bar').text(data.msg);
socket.emit('get_users');
});
// 接收服务器消息
socket.on('server_message', function(data) {
$('#chat-log').append(`<div class="server-msg">[${data.time || ''}] ${data.msg}</div>`);
scrollChatToBottom();
});
// 新消息
socket.on('new_message', function(data) {
$('#chat-log').append(`<div class="chat-msg"><span class="user">${data.username}</span>: ${data.msg} <span class="time">${data.time}</span></div>`);
scrollChatToBottom();
});
// 用户加入/离开
socket.on('user_joined', function(data) {
$('#chat-log').append(`<div class="server-msg">[${data.username} joined ${currentChannel}]</div>`);
scrollChatToBottom();
socket.emit('get_users');
});
socket.on('user_left', function(data) {
$('#chat-log').append(`<div class="server-msg">[${data.username} left ${currentChannel}]</div>`);
scrollChatToBottom();
socket.emit('get_users');
});
// 更新在线用户列表
socket.on('user_list', function(data) {
$('#online-users').empty();
data.users.forEach(user => {
$('#online-users').append(`<li>${user}</li>`);
});
$('#user-count').text(data.users.length);
});
// 发送消息
$('#send-btn').click(function() {
var msg = $('#message-input').val();
if (msg.trim()) {
socket.emit('send_message', { msg: msg, room: currentChannel });
$('#message-input').val('');
}
});
$('#message-input').keypress(function(e) {
if (e.which === 13) $('#send-btn').click();
});
// 频道切换(目前仅 general)
$('.channel-btn').click(function() {
var channel = $(this).data('channel');
socket.emit('switch_channel', { channel: channel });
$(this).siblings().removeClass('active');
$(this).addClass('active');
currentChannel = channel;
$('#chat-log').empty(); // 清空聊天记录,实际可加载历史消息(未实现)
socket.emit('get_users');
});
function scrollChatToBottom() {
var chatLog = document.getElementById('chat-log');
chatLog.scrollTop = chatLog.scrollHeight;
}
});
</script>
{% endblock %}
样式文件(static/style.css,简单美化):
body {
font-family: 'Consolas', monospace;
background: #1a1a1a;
color: #f0f0f0;
margin: 0;
padding: 0;
}
.intro {
text-align: center;
margin-top: 20vh;
}
.intro .btn {
padding: 10px 20px;
background: #007bff;
color: white;
text-decoration: none;
border-radius: 4px;
}
.irc-container {
width: 90%;
max-width: 800px;
margin: 20px auto;
background: #2b2b2b;
padding: 10px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.irc-header {
background: #333;
padding: 5px 10px;
font-weight: bold;
}
.channel-bar {
margin: 10px 0;
}
.channel-btn {
background: #444;
border: none;
color: white;
padding: 5px 10px;
margin-right: 5px;
cursor: pointer;
}
.channel-btn.active {
background: #007bff;
}
#chat-log {
padding: 10px;
background: #1e1e1e;
height: 400px;
overflow-y: auto;
font-size: 14px;
}
.chat-msg .user {
color: #4CAF50;
font-weight: bold;
}
.chat-msg .time {
font-size: 12px;
color: #888;
}
.server-msg {
color: #888;
font-style: italic;
font-size: 13px;
margin: 2px 0;
}
.user-list {
margin-top: 10px;
padding: 5px;
background: #333;
}
.user-list ul {
list-style: none;
padding: 0;
}
.user-list li {
padding: 2px 5px;
border-bottom: 1px solid #444;
}
.input-area {
margin-top: 10px;
display: flex;
}
#message-input {
width: 85%;
padding: 10px;
font-size: 14px;
background: #444;
color: white;
border: none;
}
#send-btn {
width: 15%;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}
#status-bar {
margin-top: 5px;
font-size: 13px;
color: #aaa;
}
运行步骤:
- 确保已安装
Flask 和 Flask-SocketIO(运行 pip install -r requirements.txt)。
- 运行
python app.py 启动服务器。
- 打开浏览器访问
http://127.0.0.1:5000,点击 Enter IRC 进入聊天室。
- 你会看到一个自动分配的用户名(类似
DarkByte427),然后就可以在 General 频道聊天啦!
- 打开多个浏览器窗口模拟多用户互动。
功能总结:
- 用户连接时随机分配昵称(如
NovaSpectra812)。
- 默认加入
general 频道(暂不支持自定义频道)。
- 实时聊天、用户加入/离开通知。
- 简单的用户列表显示。
- 发送消息使用 SocketIO 即时更新到所有在线用户。
- 基础的样式模仿复古风格(向 Hacknet 致敬)。
待改进点(留给你):
- 持久化存储:用户数据、聊天记录存入数据库(如 SQLite)。
- 多频道支持:允许用户创建/加入其他频道。
- 私聊功能:
/query <user> 实现两人私密对话。
- 命令系统:支持
/nick <newname> 改名、/me <action> 第三人称动作等。
- 心跳检测:避免僵尸连接。
- 身份验证:引入简单登录机制。
- 历史消息滚动加载。
- 更完善的样式:移动端适配、动画效果。
现在,尽情享(复)受(刻)Hacknet 风格的 IRC 世界吧! 🎉
注意:本示例未严格遵循 IRC 协议(RFC1459),很多细节(如数字返回码、严格的语法检查)被简化了。若想深入研究,推荐阅读:
玩得开心! 🚀