Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.9 kB
1
Indexable
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class GameServer
{
    private TcpListener listener;
    private List<TcpClient> clients = new List<TcpClient>();
    private const int port = 8000; // Nastav port podle potřeby

    public GameServer()
    {
        listener = new TcpListener(IPAddress.Any, port);
    }

    public void Start()
    {
        listener.Start();
        Console.WriteLine("Server started, listening on port " + port);

        Thread clientAcceptThread = new Thread(AcceptClients);
        clientAcceptThread.Start();
    }

    private void AcceptClients()
    {
        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            clients.Add(client);

            Thread clientThread = new Thread(() => HandleClient(client));
            clientThread.Start();
        }
    }

    private void HandleClient(TcpClient client)
    {
        NetworkStream stream = client.GetStream();

        while (client.Connected)
        {
            byte[] buffer = new byte[1024];
            int bytesCount = stream.Read(buffer, 0, buffer.Length);

            if (bytesCount > 0)
            {
                string message = Encoding.UTF8.GetString(buffer, 0, bytesCount);
                Console.WriteLine("Received message: " + message);

                BroadcastMessageToClients(message);
            }
        }
    }

    private void BroadcastMessageToClients(string message)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(message);

        foreach (var client in clients)
        {
            if (client.Connected)
            {
                NetworkStream stream = client.GetStream();
                stream.Write(buffer, 0, buffer.Length);
            }
        }
    }
}