0

As a side project, I'm working on a turn-based game. My plan was to simply send a string from one player to another describing the previous action taken. IE "Bob,MoveX,5,MoveY,3,END;"

I have a simple program which sends strings back and forth, but it requires that each side alternate sending, which won't work for me. Here are the 2 files.

Server:

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class ServerSocket1
{
    public static void Main()
    {
        try
        {
            bool status = true;
            string servermessage = "";
            string clientmessage = "";
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            TcpListener tcpListener = new TcpListener(localAddr, 8100);
            tcpListener.Start();
            Console.WriteLine("Server Started");
            Socket socketForClient = tcpListener.AcceptSocket();
            Console.WriteLine("Client Connected");
            NetworkStream networkStream = new NetworkStream(socketForClient);
            StreamWriter streamwriter = new StreamWriter(networkStream);
            StreamReader streamreader = new StreamReader(networkStream);
            while (status)
            {
                if (socketForClient.Connected)
                {
                    servermessage = streamreader.ReadLine();
                    Console.WriteLine("Client:" + servermessage);
                    if ((servermessage == "bye"))
                    {
                        status = false;
                        streamreader.Close();
                        networkStream.Close();
                        streamwriter.Close();
                        return;
                    }
                    Console.Write("Server:");
                    clientmessage = Console.ReadLine();
                    streamwriter.WriteLine(clientmessage);
                    streamwriter.Flush();
                }
            }
            streamreader.Close();
            networkStream.Close();
            streamwriter.Close();
            socketForClient.Close();
            Console.WriteLine("Exiting");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

Client:

using System;
using System.Net.Sockets;
using System.IO;
public class ClientSocket1
{
    static void Main(string[] args)
    {
        TcpClient socketForServer;
        bool status = true;
        try
        {
            socketForServer = new TcpClient("localhost", 8100);
            Console.WriteLine("Connected to Server");
        }
        catch
        {
            Console.WriteLine("Failed to Connect to server{0}:999", "localhost");
            return;
        }
        NetworkStream networkStream = socketForServer.GetStream();
        StreamReader streamreader = new StreamReader(networkStream);
        StreamWriter streamwriter = new StreamWriter(networkStream);
        try
        {
            string clientmessage = "";
            string servermessage = "";
            while (status)
            {
                Console.Write("Client:");
                clientmessage = Console.ReadLine();
                if ((clientmessage == "bye") || (clientmessage == "BYE"))
                {
                    status = false;
                    streamwriter.WriteLine("bye");
                    streamwriter.Flush();
                }
                if ((clientmessage != "bye") && (clientmessage != "BYE"))
                {
                    streamwriter.WriteLine(clientmessage);
                    streamwriter.Flush();
                    servermessage = streamreader.ReadLine();
                    Console.WriteLine("Server:" + servermessage);
                }
            }
        }
        catch
        {
            Console.WriteLine("Exception reading from the server");
        }
        streamreader.Close();
        networkStream.Close();
        streamwriter.Close();
    }
}

I plan to add plenty of functionality, but would like to sort out why I need to alternate who sends.

Note: The game only supports 2 players, so I can safely assume there will be one host (server) and one client.

  • 1
    Define "need". In your example, alternating is the only available mechanism because you are sending and receiving in a single thread. A single thread can only do one thing at a time, so you can either send or receive but not both simultaneously. As with everything else in mainstream programming environments, if you want to do more than one thing at a time (like send and receive), then you need to use some form of concurrency. Explicit threads or asynchronous APIs serve this need in C#/.NET. – Peter Duniho Oct 18 '14 at 20:51
  • That makes sense. I'm trying to figure out the easiest way to handle sending the strings back and forth. Could I set both sides up to always be ready to send and then signal an interrupt if a message is received? – user3704313 Oct 18 '14 at 21:15
  • Yes. Since you are already using network streams, you'll probably want to look at the async/await pattern in C#, used with Stream.ReadAsync and Stream.WriteAsync. There are other mechanisms, but that approach will probably be the most applicable and immediately useful in your case. – Peter Duniho Oct 18 '14 at 22:01
  • This looks like what I need, but I can't find any decent examples. Any recommendations? – user3704313 Oct 20 '14 at 20:32
  • Well, the MSDN documentation for Stream.ReadAsync has what looks like a reasonable example. http://msdn.microsoft.com/en-us/library/hh137813(v=vs.110).aspx Also, I searched SO for "async await readsync" and turned up lots of questions involving this technique. Which is not to say all the examples there are good...many of the questions involve people who did it wrong asking for help. :) But it should still be informative. I would start with MSDN though. – Peter Duniho Oct 20 '14 at 22:01

0 Answers0