2 Pluspunkte 0 Minuspunkte
Wie erstelle ich einen TCP Server in C# um Textnachrichten auszutauschen?
von  

2 Antworten

0 Pluspunkte 0 Minuspunkte

Hier ist ein einfaches Beispiel eines TCP Server in C#.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Program
{
    static void Main()
    {
        TcpListener server = null;
        try
        {
            // Setze die IP-Adresse und den Port des Servers
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 8080;

            // Erstelle einen TCP-Listener, um auf eingehende Verbindungen zu warten
            server = new TcpListener(ipAddress, port);

            // Starte den Server
            server.Start();

            Console.WriteLine("Server gestartet...");

            while (true)
            {
                Console.WriteLine("Warte auf eine Verbindung...");

                // Warte auf eine eingehende Verbindung
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Verbindung hergestellt!");

                // Verarbeitung der Client-Anforderung in einem separaten Thread (in der Praxis empfohlen)
                HandleClient(client);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Fehler: " + e);
        }
        finally
        {

            server.Stop();
        }
    }

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

        // Eine Nachricht an den Client senden
        string response = "Hallo, Client!";
        byte[] responseData = Encoding.ASCII.GetBytes(response);
        stream.Write(responseData, 0, responseData.Length);
        stream.Flush();
        
        byte[] buffer = new byte[256];
        int bytesRead = stream.Read(buffer, 0, buffer.Length);
        string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
        Console.WriteLine("Empfangene Nachricht:" + data);

        // Hier könnte die Verarbeitung der empfangenen Daten erfolgen

        // Die Verbindung schließen
        stream.Close();
        client.Close();
    }
}

von (410 Punkte)  
0 Pluspunkte 0 Minuspunkte

Hier ist ein Beispiel eines Server in C#.

using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;

public enum MessageType
{
    String,
    Int,
    Float,
    Vector3
}

[Serializable]
public struct Vector3
{
    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }

    public Vector3(float x, float y, float z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

public class Message
{
    public MessageType Type { get; set; }
    public string Content { get; set; }
    public int IntValue { get; set; }
    public float FloatValue { get; set; }
    public Vector3 VectorValue { get; set; }

    public Message(MessageType type, string content = "", int intValue = 0, float floatValue = 0.0f, Vector3 vectorValue = default(Vector3))
    {
        Type = type;
        Content = content;
        IntValue = intValue;
        FloatValue = floatValue;
        VectorValue = vectorValue;
    }

    public byte[] ToBytes()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            return stream.ToArray();
        }
    }

    public static Message FromBytes(byte[] data)
    {
        using (MemoryStream stream = new MemoryStream(data))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            return (Message)formatter.Deserialize(stream);
        }
    }
}

public class MultiplayerServer
{

    private TcpListener tcpListener;
    private Thread listenerThread;
    private List<TcpClient> connectedClients = new List<TcpClient>();

    public MultiplayerServer()
    {
        this.tcpListener = new TcpListener(IPAddress.Any, 5555);
        this.listenerThread = new Thread(new ThreadStart(ListenForClients));
        this.listenerThread.Start();
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();

        while (true)
        {
            TcpClient client = this.tcpListener.AcceptTcpClient();
            connectedClients.Add(client);

            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object clientObj)
    {
        TcpClient tcpClient = (TcpClient)clientObj;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] messageBuffer = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                bytesRead = clientStream.Read(messageBuffer, 0, 4096);
            }
            catch
            {
                break;
            }

            if (bytesRead == 0)
                break;

            Message receivedMessage = Message.FromBytes(messageBuffer);
            OnMessageReceived(receivedMessage);
            
            /*
            Message responseMessage = new Message(MessageType.String, "Server has received your message: " + receivedMessage.Content);
            SendMessageToClient(tcpClient, responseMessage);
            */

        }

        connectedClients.Remove(tcpClient);
        tcpClient.Close();
    }

    private void SendMessageToClient(TcpClient client, Message message)
    {
        NetworkStream clientStream = client.GetStream();
        byte[] messageBytes = message.ToBytes();
        clientStream.Write(messageBytes, 0, messageBytes.Length);
    }

    public void StartListening()
    {
        // Implement your game logic here for the server
    }

    protected virtual void OnMessageReceived(Message message)
    {
        MessageReceived?.Invoke(message);
    }

    public event Action<Message> MessageReceived;

}
von (732 Punkte)