我来帮你构建一个类似Hacknet风格的在线IRC系统。这个系统将使用Flask作为后端,WebSocket进行实时通信,并具有黑客风格的界面。
项目结构
hacknet-irc/
├── app.py
├── requirements.txt
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── irc.js
└── templates/
└── index.html
后端代码
requirements.txt
Flask==2.3.2
Flask-SocketIO==5.3.4
python-socketio==5.9.0
eventlet==0.33.3
app.py
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, join_room, leave_room
from datetime import datetime
import random
import string
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
socketio = SocketIO(app, cors_allowed_origins="*")
# 存储用户和频道信息
users = {}
channels = {
'#general': {'users': set(), 'messages': []},
'#random': {'users': set(), 'messages': []},
'#hacking': {'users': set(), 'messages': []},
'#underground': {'users': set(), 'messages': []}
}
# 生成随机用户ID
def generate_user_id():
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def handle_connect():
user_id = generate_user_id()
users[request.sid] = {
'id': user_id,
'nickname': f'user_{user_id[:4]}',
'current_channel': None,
'connected_at': datetime.now()
}
emit('connected', {'user_id': user_id, 'nickname': users[request.sid]['nickname']})
@socketio.on('disconnect')
def handle_disconnect():
if request.sid in users:
user = users[request.sid]
if user['current_channel']:
leave_channel(request.sid, user['current_channel'])
del users[request.sid]
@socketio.on('set_nickname')
def handle_set_nickname(data):
if request.sid in users:
old_nick = users[request.sid]['nickname']
new_nick = data['nickname']
users[request.sid]['nickname'] = new_nick
# 通知当前频道的用户
if users[request.sid]['current_channel']:
channel = users[request.sid]['current_channel']
emit('system_message', {
'message': f'{old_nick} is now known as {new_nick}',
'timestamp': datetime.now().strftime('%H:%M:%S')
}, room=channel)
@socketio.on('join_channel')
def handle_join_channel(data):
channel = data['channel']
if channel not in channels:
channels[channel] = {'users': set(), 'messages': []}
user = users[request.sid]
# 离开当前频道
if user['current_channel']:
leave_channel(request.sid, user['current_channel'])
# 加入新频道
join_room(channel)
channels[channel]['users'].add(request.sid)
user['current_channel'] = channel
# 发送频道历史消息
emit('channel_history', {
'channel': channel,
'messages': channels[channel]['messages'][-50:] # 最近50条消息
})
# 通知频道内的其他用户
emit('user_joined', {
'nickname': user['nickname'],
'channel': channel,
'timestamp': datetime.now().strftime('%H:%M:%S')
}, room=channel)
# 更新用户列表
update_user_list(channel)
@socketio.on('leave_channel')
def handle_leave_channel(data):
channel = data['channel']
leave_channel(request.sid, channel)
def leave_channel(sid, channel):
if channel in channels and sid in channels[channel]['users']:
user = users[sid]
leave_room(channel)
channels[channel]['users'].remove(sid)
user['current_channel'] = None
emit('user_left', {
'nickname': user['nickname'],
'channel': channel,
'timestamp': datetime.now().strftime('%H:%M:%S')
}, room=channel)
update_user_list(channel)
@socketio.on('send_message')
def handle_message(data):
user = users[request.sid]
channel = user['current_channel']
if not channel:
emit('error', {'message': 'You must join a channel first'})
return
message_data = {
'nickname': user['nickname'],
'message': data['message'],
'timestamp': datetime.now().strftime('%H:%M:%S'),
'channel': channel
}
# 存储消息
channels[channel]['messages'].append(message_data)
# 广播消息
emit('new_message', message_data, room=channel)
@socketio.on('list_channels')
def handle_list_channels():
channel_list = []
for channel, info in channels.items():
channel_list.append({
'name': channel,
'users': len(info['users'])
})
emit('channel_list', {'channels': channel_list})
def update_user_list(channel):
if channel in channels:
user_list = []
for sid in channels[channel]['users']:
if sid in users:
user_list.append(users[sid]['nickname'])
emit('user_list', {
'channel': channel,
'users': sorted(user_list)
}, room=channel)
if __name__ == '__main__':
socketio.run(app, debug=True, port=5000)
前端代码
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HackNet IRC</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
</head>
<body>
<div class="terminal-container">
<div class="terminal-header">
<span class="terminal-title">HackNet IRC v1.0</span>
<span class="terminal-status" id="connection-status">DISCONNECTED</span>
</div>
<div class="main-container">
<div class="sidebar">
<div class="channels-section">
<div class="section-header">CHANNELS</div>
<div id="channel-list" class="channel-list"></div>
</div>
<div class="users-section">
<div class="section-header">USERS</div>
<div id="user-list" class="user-list"></div>
</div>
</div>
<div class="chat-container">
<div id="chat-output" class="chat-output"></div>
<div class="input-container">
<span class="input-prompt" id="input-prompt">></span>
<input type="text" id="message-input" class="message-input" placeholder="Type a message or command..." autofocus>
</div>
</div>
</div>
</div>
<script src="{{ url_for('static', filename='js/irc.js') }}"></script>
</body>
</html>
static/css/style.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #0a0a0a;
color: #00ff00;
font-family: 'Courier New', monospace;
font-size: 14px;
overflow: hidden;
}
.terminal-container {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
background-color: #000;
border: 2px solid #00ff00;
}
.terminal-header {
background-color: #001100;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #00ff00;
}
.terminal-title {
font-weight: bold;
text-shadow: 0 0 10px #00ff00;
}
.terminal-status {
font-size: 12px;
padding: 2px 8px;
border: 1px solid #00ff00;
background-color: #002200;
}
.terminal-status.connected {
color: #00ff00;
border-color: #00ff00;
}
.terminal-status.disconnected {
color: #ff0000;
border-color: #ff0000;
}
.main-container {
display: flex;
flex: 1;
overflow: hidden;
}
.sidebar {
width: 200px;
background-color: #001100;
border-right: 1px solid #00ff00;
display: flex;
flex-direction: column;
}
.channels-section, .users-section {
flex: 1;
overflow-y: auto;
}
.section-header {
padding: 10px;
background-color: #002200;
border-bottom: 1px solid #00ff00;
font-weight: bold;
text-align: center;
}
.channel-list, .user-list {
padding: 10px;
}
.channel-item, .user-item {
padding: 5px;
cursor: pointer;
transition: all 0.2s;
}
.channel-item:hover {
background-color: #003300;
text-shadow: 0 0 5px #00ff00;
}
.channel-item.active {
background-color: #004400;
border-left: 3px solid #00ff00;
}
.user-item {
color: #00cc00;
font-size: 12px;
}
.chat-container {
flex: 1;
display: flex;
flex-direction: column;
background-color: #000;
}
.chat-output {
flex: 1;
overflow-y: auto;
padding: 10px;
font-size: 13px;
line-height: 1.6;
}
.message {
margin-bottom: 5px;
word-wrap: break-word;
}
.message-time {
color: #666;
margin-right: 10px;
}
.message-nick {
color: #00ff00;
margin-right: 10px;
}
.message-text {
color: #00cc00;
}
.system-message {
color: #ffff00;
font-style: italic;
}
.error-message {
color: #ff0000;
}
.input-container {
display: flex;
align-items: center;
padding: 10px;
background-color: #001100;
border-top: 1px solid #00ff00;
}
.input-prompt {
margin-right: 10px;
color: #00ff00;
}
.message-input {
flex: 1;
background-color: transparent;
border: none;
color: #00ff00;
font-family: inherit;
font-size: 14px;
outline: none;
}
.message-input::placeholder {
color: #006600;
}
/* 滚动条样式 */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #001100;
}
::-webkit-scrollbar-thumb {
background: #00ff00;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #00cc00;
}
/* 打字机效果 */
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
.cursor::after {
content: '_';
animation: blink 1s infinite;
}
static/js/irc.js
class HackNetIRC {
constructor() {
this.socket = null;
this.currentChannel = null;
this.nickname = null;
this.userId = null;
this.init();
}
init() {
this.socket = io();
this.setupSocketEvents();
this.setupUIEvents();
}
setupSocketEvents() {
this.socket.on('connect', () => {
this.updateConnectionStatus(true);
});
this.socket.on('disconnect', () => {
this.updateConnectionStatus(false);
});
this.socket.on('connected', (data) => {
this.userId = data.user_id;
this.nickname = data.nickname;
this.addSystemMessage(`Connected to HackNet IRC as ${this.nickname}`);
this.socket.emit('list_channels');
});
this.socket.on('channel_list', (data) => {
this.updateChannelList(data.channels);
});
this.socket.on('channel_history', (data) => {
this.clearChat();
this.addSystemMessage(`Joined ${data.channel}`);
data.messages.forEach(msg => {
this.addMessage(msg);
});
});
this.socket.on('new_message', (data) => {
this.addMessage(data);
});
this.socket.on('user_joined', (data) => {
this.addSystemMessage(`${data.nickname} joined ${data.channel}`);
});
this.socket.on('user_left', (data) => {
this.addSystemMessage(`${data.nickname} left ${data.channel}`);
});
this.socket.on('user_list', (data) => {
this.updateUserList(data.users);
});
this.socket.on('system_message', (data) => {
this.addSystemMessage(data.message);
});
this.socket.on('error', (data) => {
this.addErrorMessage(data.message);
});
}
setupUIEvents() {
const input = document.getElementById('message-input');
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.handleInput(input.value);
input.value = '';
}
});
}
handleInput(text) {
if (!text.trim()) return;
if (text.startsWith('/')) {
this.handleCommand(text);
} else {
if (this.currentChannel) {
this.socket.emit('send_message', { message: text });
} else {
this.addErrorMessage('You must join a channel first. Use /join #channel');
}
}
}