Hier ist ein Beispiel eines TCP Client 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 MultiplayerClient
{
private TcpClient tcpClient;
private Thread clientThread;
private NetworkStream clientStream;
public MultiplayerClient()
{
this.tcpClient = new TcpClient();
this.clientThread = new Thread(new ThreadStart(ConnectToServer));
this.clientThread.Start();
}
private void ConnectToServer()
{
this.tcpClient.Connect("127.0.0.1", 5555);
this.clientStream = this.tcpClient.GetStream();
byte[] serverResponseBuffer = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = this.clientStream.Read(serverResponseBuffer, 0, 4096);
}
catch
{
break;
}
if (bytesRead == 0)
break;
Message serverResponse = Message.FromBytes(serverResponseBuffer);
OnMessageReceived(serverResponse);
}
}
protected virtual void OnMessageReceived(Message message)
{
MessageReceived?.Invoke(message);
}
public event Action<Message> MessageReceived;
// Add other methods for sending messages, game logic, etc.
}