4

I just read and tested code of this great article in order to understand TCP Client and Server.

Now I need to do (I hope) really simple thing I need to send some string from TCP Client To TCP Server.

The string is serialized object and it is a XML in fact.

What I don't understand where I have to include this code in TCP Client and also in the TCP server.

TCP Client:

static void Main(string[] args)
    {

        while (true)
        {
            String server = "192.168.2.175"; // args[0]; // Server name or IP address

            // Convert input String to bytes
            byte[] byteBuffer = Encoding.ASCII.GetBytes("1024"); // Encoding.ASCII.GetBytes(args[1]);

            // Use port argument if supplied, otherwise default to 8080
            int servPort = 1311;  // (args.Length == 3) ? Int32.Parse(args[2]) : 8080;//7 ;

            TcpClient client = null;
            NetworkStream netStream = null;

            try
            {
                // Create socket that is connected to server on specified port
                client = new TcpClient(server, servPort);

                Console.WriteLine("Connected to server... sending echo string");

                netStream = client.GetStream();

                // Send the encoded string to the server
                netStream.Write(byteBuffer, 0, byteBuffer.Length);

                Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

                int totalBytesRcvd = 0; // Total bytes received so far
                int bytesRcvd = 0; // Bytes received in last read

                // Receive the same string back from the server
                while (totalBytesRcvd < byteBuffer.Length)
                {
                    if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                    byteBuffer.Length - totalBytesRcvd)) == 0)
                    {
                        Console.WriteLine("Connection closed prematurely.");
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }
                Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
                Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));

            }
            catch (Exception ex)
            {
                // http://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (netStream != null)
                    netStream.Close();
                if (client != null)
                    client.Close();
            }
            Thread.Sleep(1000);
        }

    }

TCP Server

class Program
{

    private const int BUFSIZE = 32; // Size of receive buffer

    static void Main(string[] args)
    {


        int servPort = 1311; // (args.Length == 1) ? Int32.Parse(args[0]) : 8080;

        TcpListener listener = null;

        try
        {
            // Create a TCPListener to accept client connections
            listener = new TcpListener(IPAddress.Any, servPort);
            listener.Start();
        }
        catch (SocketException se)
        {
            // IPAddress.Any
            Console.WriteLine(se.ErrorCode + ": " + se.Message);
            //Console.ReadKey();
            Environment.Exit(se.ErrorCode);

        }

        byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
        int bytesRcvd; // Received byte count
        for (; ; )
        { // Run forever, accepting and servicing connections
            // Console.WriteLine(IPAddress.Any);
            TcpClient client = null;
            NetworkStream netStream = null;
            //Console.WriteLine(IPAddress.None);

            try
            {
                client = listener.AcceptTcpClient(); // Get client connection
                netStream = client.GetStream();
                Console.Write("Handling client - ");

                // Receive until client closes connection, indicated by 0 return value
                int totalBytesEchoed = 0;
                while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
                {
                    netStream.Write(rcvBuffer, 0, bytesRcvd);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);

                // Close the stream and socket. We are done with this client!
                netStream.Close();
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                netStream.Close();
            }
        }
    }
}
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • I strongly suggest you use WCF, instead of implementing all the stuff yourself. In WCF, you create the interfaces (Service Contracts) and implementations (Services) and the framework abstracts all the communication / protocol details out. – Federico Berasategui Mar 11 '13 at 18:39
  • @HighCore In my architecture of the Application I have to implement TCP Client/Server will be combined. So "Client" as well as "Server" wil have those combined things. Question: Have I install then WCF application in both machine? You mean it shoulbd like "WcfService1" Client and "WcfService2" Server projects? So workstation has "WcfService1" and server "WcfService2" ? – NoWar Mar 11 '13 at 18:42
  • WCF is part of the .Net Framework. I don't understand your question. You have to install the .Net framework in the target machine anyways, otherwise your code will not run. – Federico Berasategui Mar 11 '13 at 18:45
  • 1
    No, you can use [WCF Duplex](http://realfiction.net/go/113) to have two-way communications between server and client. – Federico Berasategui Mar 11 '13 at 18:50
  • @HighCore Thanks! Iam reading now http://stackoverflow.com/questions/6064823/two-way-communcating-server-client-architecture and got you comment about WCF Duplex. Probably it is exactly what I need... – NoWar Mar 11 '13 at 19:02
  • @HighCore Put your comment about http://realfiction.net/go/113 like an answer please. It is exactly what I need. Thank you! – NoWar Mar 11 '13 at 19:51

2 Answers2

2

The example that you give is a simple 'mirror', where the TCP server sends back to the client the data that it receives from it.

The data that you want to send is in the byteBuffer variable (you are currently sending the text "1024", I believe). So instead of initializing it with "1024", you could initialize it with the XML-serialized data that you want.

On the client side, conversely, instead of echoing the data back to the client, you could simply do whatever you need on the server side with the data, that is your XML object.

lmsteffan
  • 840
  • 4
  • 13
2

Converting my Comments into an answer:

I strongly suggest you use WCF, instead of implementing all the stuff yourself. In WCF, you create the interfaces (Service Contracts) and implementations (Services) and the framework abstracts all the communication / protocol details out.

You can use WCF Duplex to have two-way communications between server and client

Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154