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;
}