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!