Untitled
unknown
plain_text
3 years ago
1.8 kB
5
Indexable
using System.Net.Sockets;
using System.Text;
public class NetworkPlayer
{
private TcpClient client;
private NetworkStream stream;
private bool isConnected = false;
public NetworkPlayer(TcpClient client)
{
this.client = client;
this.stream = client.GetStream();
this.isConnected = true;
}
public void SendMessage(string message)
{
if (!isConnected)
{
throw new InvalidOperationException("Not connected to the server.");
}
// Convert the message to bytes
byte[] messageBytes = Encoding.ASCII.GetBytes(message);
// Send the message to the server
stream.Write(messageBytes, 0, messageBytes.Length);
}
public string ReceiveMessage()
{
if (!isConnected)
{
throw new InvalidOperationException("Not connected to the server.");
}
// Create a buffer to hold the incoming data
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
// Convert the bytes to a string
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
return message;
}
public void SendMove(int x, int y)
{
if (!isConnected)
{
throw new InvalidOperationException("Not connected to the server.");
}
// Convert the move to a string
string move = x.ToString() + "," + y.ToString();
// Send the move to the server
SendMessage(move);
}
public void Disconnect()
{
if (isConnected)
{
stream.Close();
client.Close();
isConnected = false;
}
}
}
Editor is loading...