🔌 websocket
WebSocket Protocol - Real-Time Bidirectional Communication
~800 lines
~45 function
RFC 6455
📖 Overview
WebSocket modülü, RFC 6455 uyumlu tam özellikli WebSocket client and server sağlar. Real-time chat, live notifications, multiplayer games and IoT for idealdir.
🔑 Key Features
- RFC 6455 compliant
- Client & server support
- Text & binary messages
- Ping/pong keepalive
- Message fragmentation
- UTF-8 validation
- Graceful close handshake
- Event-driven API
🚀 Quick Start - Client
import websocket olarakws
function main() do
// Connect
let client = ws.connect("ws://localhost:8080")?
// Event handlers
client.on_open(|| do
io.println("Connected!")
end)
client.on_message(|msg| do
io.println("Received: {}", msg.text())
end)
// Send message
client.send_text("Hello Server!")?
// Keep alive
client.run()
end
💡 Example: Real-Time Chat Server
import websocket olarakws, thread, collections
struct ChatServer do
clients: Map[int, ws.Connection],
next_id: int
end
function chat_server_new() -> ChatServer do
ChatServer do
clients: Map.new(),
next_id: 1
end
end
function broadcast(server: ChatServer, message: str, sender_id: int) do
each (id, client) in server.clients for do
if id != sender_id do
client.send_text(message).ok()
end
end
end
function handle_client(server: ChatServer, conn: ws.Connection, client_id: int) do
io.println("Client {} connected", client_id)
// Welcome message
conn.send_text("Welcome to chat! Your ID: {}".formatla(client_id))?
// Announce to others
broadcast(server, "User {} joined".formatla(client_id), client_id)
// Message loop
loop do
let msg = conn.receive()?
match msg.opcode do
ws.TEXT => do
let text = msg.text()
io.println("[{}] {}", client_id, text)
// Broadcast to all
let broadcast_msg = "[{}] {}".formatla(client_id, text)
broadcast(server, broadcast_msg, client_id)
end,
ws.CLOSE => do
io.println("Client {} disconnected", client_id)
server.clients.remove(client_id)
broadcast(server, "User {} left".formatla(client_id), client_id)
kır
end,
ws.PING => do
conn.send_pong(msg.data)?
end,
_ => do end
end
end
end
function main() do
let server = chat_server_new()
let ws_server = ws.listen("0.0.0.0:8080")?
io.println("Chat server listening on ws://localhost:8080")
loop do
// Accept new connections
let conn = ws_server.accept()?
let client_id = server.next_id
server.next_id += 1
server.clients.insert(client_id, conn.clone())
// Spawn thread for each client
thread.spawn(|| do
handle_client(server, conn, client_id)
end)
end
end
💡 Example: Live Dashboard (Data Streaming)
import websocket olarakws, time, thread, json
struct SystemStats do
cpu_usage: float,
memory_usage: float,
disk_usage: float,
timestamp: time.Instant
end
function collect_stats() -> SystemStats do
SystemStats do
cpu_usage: sys.cpu_usage(),
memory_usage: sys.memory_usage(),
disk_usage: sys.disk_usage(),
timestamp: time.now()
end
end
function stream_stats_to_client(conn: ws.Connection) do
io.println("Dashboard client connected")
loop do
// Collect system stats
let stats = collect_stats()
// Send as JSON
let json_data = json.encode(stats)
match conn.send_text(json_data) do
Ok(_) => do end,
Error(_) => do
io.println("Client disconnected")
kır
end
end
// Update every second
thread.sleep_ms(1000)
end
end
function main() do
let server = ws.listen("0.0.0.0:8080")?
io.println("Dashboard server: ws://localhost:8080")
loop do
let conn = server.accept()?
thread.spawn(|| do
stream_stats_to_client(conn)
end)
end
end
// HTML Client
// <script>
// const ws = new WebSocket('ws://localhost:8080');
// ws.onmessage = (e) => {
// const stats = JSON.parse(e.data);
// document.getElementById('cpu').textContent = stats.cpu_usage + '%';
// document.getElementById('memory').textContent = stats.memory_usage + '%';
// };
// </script>
🎮 Use Cases
- Real-time chat applications
- Live notifications
- Multiplayer games
- Stock/crypto price feeds
- IoT device communication
- Collaborative editing
- Live dashboards
🔗 Related Modules
http- HTTP upgradenetwork- Socket operationsjson- Message serialization