1

I have two C# programs interacting via TCP/IP synchronous communication. One of the essential libraries I'm using is System.Net.Sockets. The server is written in C# Windows form while the client is in console only. The latter is such because it will be interfaced with a microcontroller, so having it in Windows form is most likely not possible and unnecessary.

I have successfully sent data from the server to the client. Now, I'm working on sending data from the client to the server once you've pressed certain keys. I am using keys for simulation purposes since the device that will give the data are fingerprint scanner, barcode reader, and magnetic lock. Once you've pressed number 1, for example, the program will send a data. I've successfully sent data from the client to the server using hardcoding. My problem is on synchronous reading and writing at the client socket.

In both C# programs, read() is threaded. For the server, write() is activated once you've pressed a button; for the client, once you've pressed a key on the keyboard.

I've read different forums and applied methods such as using Console.KeyAvailable, delegate, threading, but I can't execute them properly. I have little successes with the latter two but for the Console.KeyAvailable, I can write and read to and from the socket but there are errors on synchronization.

Here's my send() and receive() codes for client.

//********************SEND DATA TO CLIENT********************
static void sendToClient()
{
    if (client.Connected)
    {
        sendBuffer = new Byte[1024];
        try
        {
            device = Console.Read();
            #region Data to send per device
            switch (device)
            {
                case 1: // barcode
                    {
                        dataToSend = "bar1234";
                    }
                    break;
                case 2: // fingerprint
                    {
                        dataToSend = "fingerprint5678";
                    }
                    break;
                case 3: // lock
                    {
                        dataToSend = "lock8910";
                    }
                    break;
                default:
                    break;
            }
            #endregion

            sendStream = client.GetStream();
            sendBuffer = Encoding.ASCII.GetBytes(dataToSend);
            sendStream.Write(sendBuffer, 0, sendBuffer.Length);
            Console.WriteLine("Data sent!");

            Console.Clear();
            sendStream.Flush();
        }
        // insert catch statements
    }
}

//********************RECEIVE DATA FROM CLIENT********************
static void receiveFromClient()
        {
            receiveStream = client.GetStream();
            try
            {
                sendToClient();
                strReceivedData = new StringBuilder();
                receiveBuffer = new Byte[1024];
                while(client.Connected)
                {
                    while (!(Console.KeyAvailable))
                    {
                        try
                        {
                            byteRead = receiveStream.Read(receiveBuffer, 0, receiveBuffer.Length);
                        }
                        // insert catch statements
                        strReceivedData.AppendFormat("{0}", Encoding.ASCII.GetString(receiveBuffer, 0, byteRead));
                        Console.WriteLine(strReceivedData.ToString());

                        strReceivedData.Clear();
                        receiveStream.Flush();
                    }
                    if (Console.KeyAvailable)
                        sendToClient();
                }
            }
             // insert catch statements
        }
    }
}

Question is, how do you synchronize these two things?

  • Waiting for a user input then writing to a socket
  • Listening/reading from a socket

Any help is appreciated. Thanks!

ellekaie
  • 337
  • 1
  • 7
  • 21
  • What is the question or problem? From your question I don't see what exactly is the problem. – Sriram Sakthivel Nov 30 '14 at 10:13
  • How do you accept input then write to the socket _while_ reading from the socket? – ellekaie Nov 30 '14 at 10:16
  • Is receive synchronous? I mean will you get data from server any time or only if you send data you'll get response? – Sriram Sakthivel Nov 30 '14 at 10:19
  • You can receive data from server any time. – ellekaie Nov 30 '14 at 10:20
  • There are several options, use dedicated threads for sending(reading data from device and send) and receiving. Or use asynchronous IO to recieve, you can still use synchronous to send to make it easier. etc. Again, It seems you have all the code in place, I still don't understand what exactly is the problem. So no specific answer sorry. – Sriram Sakthivel Nov 30 '14 at 10:25
  • Yes, I've used threading as my `receive()` function is threaded. From your second question above I'm now thinking whether my program should be synchronous or asynchronous (I haven't quite grasped the difference between the two). The code is running but is producing erroneous results. – ellekaie Nov 30 '14 at 10:43
  • I don't see why all of this has to happen on a single thread. Use one thread for the console and one for the socket. That makes all of this reasonably straight forward. If you find yourself writing polling loops - redesign! – usr Nov 30 '14 at 10:46
  • What do you mean one for the console and one for the socket? – ellekaie Nov 30 '14 at 10:48
  • @usr Sorry I didn't quite understand. Console is like the user interface for my client, while socket is a different entity (I think). – ellekaie Nov 30 '14 at 10:52
  • There are lots of examples online. Here's one I wrote last month: http://stackoverflow.com/a/26917806/3538012. It's hard to answer a question if you don't ask a specific one, but generally speaking: you _don't_ necessarily need to synchronize reading and writing, depending on what you're trying to do. As you can see in my example, the client (console) runs in the main thread handling user input and sending it, with the receiving handled asynchronously. What little synchronization between threads is needed, is implicit in the `Console` class. No additional synchronization is needed. – Peter Duniho Nov 30 '14 at 20:27
  • Update: Just like what @usr had explicitly suggested, I started all over again. From synchronous I am now writing my code in async. – ellekaie Dec 10 '14 at 20:42

0 Answers0