🔌 websocket

WebSocket Protocol - Real-Time Bidirectional Communication

~800 satır ~45 fonksiyon RFC 6455

📖 Genel Bakış

WebSocket modülü, RFC 6455 uyumlu tam özellikli WebSocket client ve server sağlar. Real-time chat, live notifications, multiplayer games ve IoT için idealdir.

🔑 Temel Özellikler

🚀 Hızlı Başlangıç - Client

içe_aktar websocket olarakws

fonksiyon ana() yap
    // Connect
    değişken client = ws.connect("ws://localhost:8080")?
    
    // Event handlers
    client.on_open(|| yap
        io.println("Connected!")
    son)
    
    client.on_message(|msg| yap
        io.println("Received: {}", msg.text())
    son)
    
    // Send message
    client.send_text("Hello Server!")?
    
    // Keep alive
    client.run()
son

💡 Örnek: Real-Time Chat Server

içe_aktar websocket olarakws, thread, collections

yapı ChatServer yap
    clients: Map[sayı, ws.Connection],
    next_id: sayı
son

fonksiyon chat_server_new() -> ChatServer yap
    ChatServer yap
        clients: Map.new(),
        next_id: 1
    son
son

fonksiyon broadcast(server: ChatServer, message: yazı, sender_id: sayı) yap
    her (id, client) içinde server.clients için yap
        eğer id != sender_id ise yap
            client.send_text(message).ok()
        son
    son
son

fonksiyon handle_client(server: ChatServer, conn: ws.Connection, client_id: sayı) yap
    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
    döngü yap
        değişken msg = conn.receive()?
        
        eşle msg.opcode yap
            ws.TEXT => yap
                değişken text = msg.text()
                io.println("[{}] {}", client_id, text)
                
                // Broadcast to all
                değişken broadcast_msg = "[{}] {}".formatla(client_id, text)
                broadcast(server, broadcast_msg, client_id)
            son,
            
            ws.CLOSE => yap
                io.println("Client {} disconnected", client_id)
                server.clients.remove(client_id)
                broadcast(server, "User {} left".formatla(client_id), client_id)
                kır
            son,
            
            ws.PING => yap
                conn.send_pong(msg.data)?
            son,
            
            _ => yap son
        son
    son
son

fonksiyon ana() yap
    değişken server = chat_server_new()
    değişken ws_server = ws.listen("0.0.0.0:8080")?
    
    io.println("Chat server listening on ws://localhost:8080")
    
    döngü yap
        // Accept new connections
        değişken conn = ws_server.accept()?
        
        değişken client_id = server.next_id
        server.next_id += 1
        server.clients.insert(client_id, conn.clone())
        
        // Spawn thread for each client
        thread.spawn(|| yap
            handle_client(server, conn, client_id)
        son)
    son
son

💡 Örnek: Live Dashboard (Data Streaming)

içe_aktar websocket olarakws, time, thread, json

yapı SystemStats yap
    cpu_usage: kesir,
    memory_usage: kesir,
    disk_usage: kesir,
    timestamp: time.Instant
son

fonksiyon collect_stats() -> SystemStats yap
    SystemStats yap
        cpu_usage: sys.cpu_usage(),
        memory_usage: sys.memory_usage(),
        disk_usage: sys.disk_usage(),
        timestamp: time.now()
    son
son

fonksiyon stream_stats_to_client(conn: ws.Connection) yap
    io.println("Dashboard client connected")
    
    döngü yap
        // Collect system stats
        değişken stats = collect_stats()
        
        // Send as JSON
        değişken json_data = json.encode(stats)
        
        eşle conn.send_text(json_data) yap
            Tamam(_) => yap son,
            Hata(_) => yap
                io.println("Client disconnected")
                kır
            son
        son
        
        // Update every second
        thread.sleep_ms(1000)
    son
son

fonksiyon ana() yap
    değişken server = ws.listen("0.0.0.0:8080")?
    
    io.println("Dashboard server: ws://localhost:8080")
    
    döngü yap
        değişken conn = server.accept()?
        
        thread.spawn(|| yap
            stream_stats_to_client(conn)
        son)
    son
son

// 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

🔗 İlgili Modüller

← Tüm Modüller