Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
0
Indexable
Never
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TicTacToe
{
    public class NetworkPlayer
    {
        private TcpClient client;
        private NetworkStream stream;

        private string serverAddress;
        private int serverPort;

        public NetworkPlayer(string serverAddress, int serverPort)
        {
            this.serverAddress = serverAddress;
            this.serverPort = serverPort;
        }

        public void Connect()
        {
            client = new TcpClient(serverAddress, serverPort);
            stream = client.GetStream();
        }

        public void SendMove(int x, int y)
        {
            byte[] data = Encoding.UTF8.GetBytes($"{x},{y}");
            stream.Write(data, 0, data.Length);
        }

        public (int x, int y) ReceiveMove()
        {
            byte[] data = new byte[256];
            int bytes = stream.Read(data, 0, data.Length);
            string responseData = Encoding.UTF8.GetString(data, 0, bytes);
            string[] parts = responseData.Split(',');
            return (int.Parse(parts[0]), int.Parse(parts[1]));
        }


        public void Disconnect()
        {
            stream.Close();
            client.Close();
        }
    }
}