Reading data from device connected through TCP - c#

I have device (TCP/IP network controller) which is connect to my network router. To that controller is connected fingerprint scanner. What i want to do is get data of scanned finger into my c# code.
I have tried using TCP Listner but nothing happened (no error or anything lese)
I have dll file from that product but there are lot of code in it and i am new to this so i overlooked something. Inside that dll i tried searching for some EventHandler (thought that is listening or responding when finger is placed on scanner) but there is not even one of it.
What should i look for or how should i listen to data that get's sent from that device.
Here is DLL File: Download Link
I know this may be too broad but please give me some hints, i am trying this for few days and still can't figure it out.
Code i tried:
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 60000.
Int32 port = 60000;
// TcpListener server = new TcpListener(port);
server = new TcpListener(port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}
Product i am having: LINK
Couldn't find any documentation for it.

Related

Is there a way to get tcp server to send responses other than echoing incoming messages?

I am obviously new to TCP servers.
The code below works just fine - It "only" echoes the messages it receives.
But my question is "simple": How can I send responses to my client - other than simply echoing the request as I do below?
For instance, if I wanted to send data back (specifically for me, "OFML" data in XML like form for criminal justice end-users).
But I'd settle for "Hello world!"!
All my attempts to do this result in my client crashing (the proprietary code of which I cannot share) - and some customized error messages like, "NO Packet Found".
Any suggestions would be most appreciated - or references to some clear documentation on how to accomplish this.
Oh - and I might add I am simply trying to create a simple "mock" server for local debugging of the client - i.e this will never be for "production".
Thanks!
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading;
namespace FoxTalkMOCK
{
class Program
{
public static void Main()
{
TcpListener server = null;
try
{
Int32 port = 8080;
IPAddress localAddr = IPAddress.Parse("10.116.45.49");
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[18];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
string bitString = BitConverter.ToString(bytes);
bitString = bitString.Replace("-", ", 0x");
bitString = "0x" + bitString;
Console.WriteLine(bitString);
// *******************Send response*********************
stream.Write(bytes, 0, bytes.Length);
Console.WriteLine("Sent: {0}", System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}```
The example connects and receives data, then sends that data back and disconnects.
If you want to keep the socket, keep it without breaking.
Whenever you save it and write it again, you can manage whether the socket is maintained through exception handling.
The answer to simply returning a "hello world" is as follows:
var strBuffer = "Hello World!";
byte[] array = new byte[strBuffer.Length];
array = System.Text.Encoding.ASCII.GetBytes(strBuffer);
stream.Write(array, 0, array.Length)

TcpListener and TcpClient connection fails when changing from localhost to actual IP address

I'm attempting to create a simple piece of software to 'chat' between two computers to test out Networking. At the moment, all I have done is copied the TcpListener (https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=netframework-4.8) and TcpClient (https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.8) code to see how it works (code at end).
It all works great, but once I replace localhost ("127.0.0.1") in both files with my actual IP address (my IPv4 address that I got by typing 'ipconfig' into the command console on windows), the two won't connect.
Are there some settings I need to configure? Is this a firewall issue or something? Or am i just being super dumb? I am pretty new to C# networking.
Thanks for any help!
TcpListener:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
TcpClient:
using System;
using System.Net.Sockets;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Connect("127.0.0.1", "Test");
}
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
}
}
Edit:
I DO get an exception, sorry:
SocketException: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [IPv4]:13000
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(IPAddress address, Int32 port)
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)
at Client.Client.Connect(String server, String message) in C:\Users\[User]\Documents\[User]\Programming\GenericC#\Client\Client.cs:line 22
easy enough to test and see if it is a firewall issue.
Open a command prompt
Type command telnet " " so you'd do on the machine stating the connection.If no error you're having a clear path and your application accepted the connection.
Have a look at the Firewall logs to see if a issue was
generated.
If possible you should allow your application to communicate in and out (if both are needed)
if you need to you could open the ports with your code (need elevated permission) if you see that the rule is missing. StackOverfow has quite a few example for this

C# and Processing socket communication

I am trying to develop a software (in C#) that collect some data on a list (List<string> socketList). The value of this list must be sent to a processing software.
In this program, the server (the C# software) waits for a message from a client (the Processing software) and send an element of the list. This list is continuously filled by a method in another thread (I verify, the list is everytime full). I used this method because I need that each value has to arrive at a client, no matter the speed.
Here there is the method in C# (it is launched as a thread):
public static void InizializeSocket()
{
//setting the comunication port
int port = 5000;
//infinite loop in order to accept sequential clients
while (true)
{
//I open the listener for any IP
TcpListener listener = new TcpListener(IPAddress.Any, port);
Console.WriteLine("Listening...");
//Waiting for a client
listener.Start();
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("CONNECTED");
//this string will contain the client message
String dataReceived = "";
//loop until "q". If the client send a message with a q, the server disconnect the client
while (dataReceived != "q")
{
//Read the client message
NetworkStream nwStream = client.GetStream();
try
{
//Define the client message buffer dimension and read the message
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//Encoding the byte in a string
dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
//check if the List<string> socketList is not empty. If it has any elements, I send the first one and after that I remove the element from the list
if (socketList.Count > 0)
{
//Encoding the string in a byte
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(socketList[0]);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
socketList.RemoveAt(0);
}
nwStream.Flush();
}
catch (Exception e) { dataReceived = "q"; }
}
//Exit from the client loop
Console.WriteLine("DISCONNECTED");
client.Close();
listener.Stop();
}
}
And here the simple Processing software
import processing.net.*;
Client myClient;
String dataIn;
int port = 5000;
String ip = "127.0.0.1";
void setup () {
size(1100, 1025);
//Initialize the client
myClient = new Client(this, "127.0.0.1", 5000);
}
void draw () {
//If the client is available it send a generic message to the server and try to receive a response
if (myClient.available() > 0) {
myClient.write("c");
dataIn = myClient.readString();
}
//print the output in debug
println(dataIn);
}
Here the Processing software is able to connect, anyway, I received every time null.
In addition, if I try to write (in the try on the C# software) only:
if (socketList.Count > 0)
{
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(socketList[0]);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
socketList.RemoveAt(0);
}
I receive strange values that are not the same values in the list stored in C# software.
So, why in the first case processing read only null value? And why in the second case it read "random" value?
EDIT:
Analyze better the programs flow, I verify where is the problem. I rewrite the processing socket as a java socket. It is launched in another thread and fills an ArrayList.
Considering a simplification of the code (in order to understand better), if I write:
Socket s = new Socket("localhost", 5000);
BufferedReader input =new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out= new PrintWriter(s.getOutputStream(), true);
out.println("hello");
String temp = input.readLine();
the software blocks on String temp = input.readLine();. Anyway, the communication is established and I am sure that C# send the string.

TcpListener doesn't accept TcpClient

The below code is Microsoft's code sample for TcpListener but I can't run that:
using System;
using System.Net;
using System.Net.Sockets;
public class TcpListenerSample
{
static void Main(string[] args)
{
try
{
// set the TcpListener on port 13000
int port = 13000;
TcpListener server = new TcpListener(IPAddress.Any, port);
// Start listening for client requests
server.Start();
// Buffer for reading data
byte[] bytes = new byte[1024];
string data;
//Enter the listening loop
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sent: {0}", data));
i = stream.Read(bytes, 0, bytes.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Hit enter to continue...");
Console.Read();
}
}
The code is stay into the loop in this line:
TcpClient client = server.AcceptTcpClient();
I've turned the firewall off but nothing changed.
How can I solve this?
AcceptTcpClient() is a blocking call which will block until a client has connected to your TcpListener. Therefore you need to use some kind of client application to test your server and connect to it. You could use Putty for this.

cannot recieve data from c# tcp server

i've wrote a simple Tcp server in C#:
(I've replaced some of the code parts in "do some stuff", when it doesn't have anything to do with the server.
now, when I try to contact the server from a python client, or an android client, I get errors such as : "the other party actively refused connection". what am I supposed to do? is the problem in my C# code, or am I probably not contacting it correctly?
thank you.
public bool ListenLoop(Int32 port, IPAddress localAddr)
{
try
{
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
//Waiting for a connection
// Perform a blocking call to accept requests.
TcpClient client = server.AcceptTcpClient();
//connected!
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//handling opCodes
if(data[0] == '0') //log in
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
else if (data[0] == '1') //download tune names
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response); //response is the names
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
else if (data[0] == '2') //changing choice
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException)
{
return false;
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
Are you sure that there is no firewall that blocks the incoming connection (as it is TCP)?
Also if your server is in testing, you should write some output to either a log file or even just to console. At least you know what is going on.
server = new TcpListener(localAddr, port);
change to
server = new TcpListener(port);

Categories

Resources