I'm working on a game version of Game of the Generals (board game). Basically, it plays like checkers, but I wanted to add multiplayer functionality, with an additional chat function. A player starts a server, another player on another PC (in the same network) starts a client, client connects to server, then they send data to each other (supposedly a 2D array containing pieces).
I've been researching on TCP Sockets and threads and stuff, but none are noob friendly and all of them use some pretty technical words and functions I've never seen before, which, I'd like to assume, means my early work on the program will be scrapped.
So, basically, I'd like to ask, what is the easiest approach to this? A friend told me multi-threaded sockets would do the trick, while another said something about asynchronous or something. Still, another suggested .NET remoting stuff.
How would you do this? A permanent loop?
So far, here's what I have:
For the server, the following code is loaded on Form Load. The program can never load the form, though. I'm assuming it has something to do with the while loop.
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start(2);
clientSocket = serverSocket.AcceptTcpClient();
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
lblStatusBar.Text = " >> Data from client - " + dataFromClient;
string serverResponse = "Server response " + Convert.ToString(requestCount);
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
And this is for the Client:
clientSocket.Connect(txtIPAd.Text, 8888);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("Message from Client$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
lblStatusBar.Text = returndata;
Again, pretty basic stuff. If I use the same PC as a client and a server, the client responds. When I put the client on a different PC, the client returns a "No connection could be made because the target machine actively refused it."
My Server machine is Windows 7, and my Client Machine is Windows Vista. Both programs are allowed through the firewall, and both are running as administrator.