How to check and ignore message from serial port? - c#

i want to ignore all messages that came to serial port except unique. i add each message to hashSet and when new message arrive i check that this messages not contains in hashSet, if this message not contains i want to print him, right now my program think that each messages arrived is unique and i don't understand why my comparing code not working, maybe somebody can help me. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace mySniffer
{
class Program
{
static void Main(string[] args)
{
HashSet<String> messages = new HashSet<String>();
SerialPort comPort = new SerialPort();
comPort.BaudRate = 115200;
comPort.PortName = "COM4";
comPort.Open();
while (true)
{
string rx = comPort.ReadLine(); //reading com port
messages.Add(rx); // Add new incoming message to hashSet
if (!messages.Contains(rx))
{
Console.WriteLine(rx); // write incoming message
}
else {
Console.WriteLine(messages.Count); // check how many messages in hashSet
}
}
}
}
}

The problem was in logic of code, messages.Add(rx); should be moved in if block.

Related

Send data to specific client from another client with a server in middle[C#]

I have searched everywhere but couldn't find as they are all answering to send message to all clients. What I want to achieve is multiple clients request to server to request data from another client and other client sends data to server telling it that data is for requesting client and so. I don't know how to achieve this. I'm new to this.
What I want to achieve:
I have tried with Data sending client to listen and requesting client to connect to it and transfer data. I have achieved this on local network but to make it work online it needs port forwarding and my user will be a lot of different people so port forwarding is not possible for every user. So I can rent a server which will act as a center of transfer. I programmed a test server in console which will listen to a server IP:port X and accept new clients and their data on port X and forward it to server IP:port Y but what this does is send data to all clients on port Y. I cannot send it to clients public ip address directly for obvious reasons. I understand that all the requesting clients are connected to port Y but I cannot create and assign new ports to all the clients interacting. So I want a way to determine how to request and receive the data without the need of assigning or creating new ports to different clients on same server.
What I have tried:
Server code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Test___server
{
class server
{
public static string serverIP = "192.168.0.102";
static void Main(string[] args)
{
Thread listenSendingThread = new Thread(listenSending);
listenSendingThread.IsBackground = true;
listenSendingThread.Start();
Thread listenReceivingThread = new Thread(listenReceiving);
listenReceivingThread.IsBackground = true;
listenReceivingThread.Start();
Console.ReadKey();
}
public static List<TcpClient> listSending = new List<TcpClient>();
public static List<TcpClient> listReceiving = new List<TcpClient>();
public static TcpClient clientSending = null;
private static void listenSending()
{
TcpListener listenerSending = new TcpListener(IPAddress.Parse(serverIP), 5319);
listenerSending.Start();
Console.WriteLine("Server listening to " + serverIP + ":5319");
while(true)
{
clientSending = listenerSending.AcceptTcpClient();
listSending.Add(clientSending);
Console.WriteLine("Sender connection received from " + clientSending.Client.RemoteEndPoint);
}
}
private static void send()
{
StreamWriter sw = new StreamWriter(clientSending.GetStream());
sw.WriteLine(message);
sw.Flush();
Console.WriteLine("Message sent!");
}
public static string message = string.Empty;
private static void listenReceiving()
{
TcpListener listener = new TcpListener(IPAddress.Parse(serverIP), 0045);
listener.Start();
Console.WriteLine("Server listening to " + serverIP + ":0045");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
listReceiving.Add(client);
Console.WriteLine("Receiver connection received from " + client.Client.RemoteEndPoint);
StreamReader sr = new StreamReader(client.GetStream());
message = sr.ReadLine();
send();
}
}
}
}
Requesting client code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test____admin
{
class admin
{
static void Main(string[] args)
{
Console.WriteLine("Begin");
string serverIP = "192.168.0.102";
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect(serverIP, );
Console.WriteLine("Connected");
while (true)
{
Console.WriteLine("Reading");
StreamReader sr = new StreamReader(clientSocket.GetStream());
Console.WriteLine("Message: " + sr.ReadLine());
}
}
}
}
Request satisfying client code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Test___client
{
class client
{
public static string serverIP = "192.168.0.102";
static void Main(string[] args)
{
clientConnect();
}
private static void clientConnect()
{
try
{
TcpClient client = new TcpClient(serverIP, 0045);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine("Karan!");
sw.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You are using a very low-level API, and doing it the right way is challenging. Instead, try YARP as a reverse proxy. The requesting client should notify the reverse proxy about the desired destination client. One option is sending the destination client name in the request header. You will also need to split a single server request into multiple client requests, then merge their responses into a single one. You can achieve it by implementing Transphorms.
I'm not sure this approach applies to your situation because clients should implement server API using REST, Grpc or any other supported technology.

C# and SerialPort formatting output

I want to get position of my motor by using command "POS;", but I get this output "a ⌂▲ yI ° y" what with this if I can get numbers?
Then from time to time I get empty answer I was answered that it take some time to get output via Serial Port. What I have to add to my code to wait until I wil get full output to show?
Manual controller (update manual)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort();
sp.PortName = "COM1";
sp.BaudRate = 9600;
sp.Open();
sp.Encoding = System.Text.Encoding.GetEncoding(28591);
if (sp.IsOpen)
{
sp.Write("ENA;");
sp.Write("POS;");
string msgPos = sp.ReadExisting();
Console.WriteLine(msgPos);
sp.Write("OFF;");
sp.Close();
Console.ReadKey();
}
}
}
}
Just add a Thread.Sleep(50) betwen the send the write and the read command. 50 miliseconds should be enough if not try a longer time.
//Do something
sp.Write("POS;");
Thread.Sleep(50);
string msgPos = sp.ReadExisting();
//Do something else
I can't find any command POS; in the manual you posted. Do you mean FBK on page 15?

How to get Monotorrents DHT to work?

Iam trying to get the dht implementation of monotorrent to work but i just cant seem to find any peers.
ive tried most of the examplecode code availeble on the net like the testclient and dhttest.
I have tried with several diffrent infohashes.
Anyone here got it working? or do you know where i can find the devs?
This is how my code looks atm:
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Dht;
using MonoTorrent.Dht.Listeners;
using System.Net;
using System.IO;
using MonoTorrent.Common;
using MonoTorrent.Tracker.Listeners;
namespace SampleClient
{
class Program
{
static void Main(string[] args)
{
string basePath = Environment.CurrentDirectory;
string torrentsPath = Path.Combine(basePath, "Torrents");
Torrent torrent = null;
// If the torrentsPath does not exist, we want to create it
if (!Directory.Exists(torrentsPath))
Directory.CreateDirectory(torrentsPath);
// For each file in the torrents path that is a .torrent file, load it into the engine.
foreach (string file in Directory.GetFiles(torrentsPath))
{
if (file.EndsWith(".torrent"))
{
try
{
// Load the .torrent from the file into a Torrent instance
// You can use this to do preprocessing should you need to
torrent = Torrent.Load(file);
Console.WriteLine(torrent.InfoHash.ToString());
}
catch (Exception e)
{
Console.Write("Couldn't decode {0}: ", file);
Console.WriteLine(e.Message);
continue;
}
}
}
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
DhtEngine engine = new DhtEngine(listener);
//engine.RegisterDht(dht);
byte[] nodes = null;
if (File.Exists("mynodes"))
nodes = File.ReadAllBytes("mynodes");
listener.Start();
int i = 0;
bool running = true;
StringBuilder sb = new StringBuilder(1024);
while (running)
{
engine.Start(nodes);
while (Console.ReadLine() != "q")
{
engine.GetPeers(torrent.InfoHash);
}
File.WriteAllBytes("mynodes", engine.SaveNodes());
}
}
}
}
I know it's very old question, I'm not sure why it's still noone has answer it, anyway. The problem seem to be this line:
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
This ip is not the real ip, so you actually asl peers to send the respone to unkonw adress.
What to do? register your own adress.

Client / Server multi threaded using TCP Listener and Streamreader / writer

I've been asked to write a Client / Server application in C#, and have been given half-completed code to get started.
It uses the ThreadPool, and TcpListener with StreamReader and StreamWriter classes for data transfer.The client has a working directory, which is fixed. The server has one too, but can change.
Basically, you type in an option on the client using a switch statement, and the server processes that option and sends it back to the client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Security.Cryptography;
namespace Client
{
/// <summary>
/// Remote File Service client
/// </summary>
class Client
{
/// <summary>
/// Static entry point to client code
/// </summary>
/// <param name="args">unused</param>
static void Main(string[] args)
{
string dir = #"c:\st12_13d1_files";
try
{
Directory.SetCurrentDirectory(dir);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("The specified directory does not exist. {0}", e);
}
try
{
using (TcpClient client = new TcpClient("localhost", 50012))
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
string option;
do
{
Console.WriteLine("-Menu-\n");
Console.WriteLine("1-Print out file names-\n");
Console.WriteLine("2-Current Working Directory-\n");
Console.WriteLine("3-Files Present on the Server-\n");
Console.WriteLine("4- List of Subdirectory Names-\n");
Console.WriteLine("5- Change Server Directory Location-\n");
Console.WriteLine("6-Copy the contents of a file specified-\n");
Console.WriteLine("7-Close-\n");
Console.WriteLine("Please enter your choice: ");
option = Console.ReadLine();
switch (option)
{
case "1":
case "one":
Console.WriteLine("You have selected Print out file names: ");
break;
}
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
namespace Server
{
/// <summary>
/// Remote File Service main functionality
/// </summary>
public class ServerMainline
{
public ServerMainline()
{
/*
* *** TO DO - your code goes here ***
* record initial current working directory value in a global variable
*/
string serv = (#"..\..");
try
{
//Set the current directory.
Directory.SetCurrentDirectory(serv);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("The specified directory does not exist. {0}", e);
}
TcpListener server = null;
try
{
ThreadPool.SetMaxThreads(50, 50);
server = new TcpListener(IPAddress.Any, 50012);
server.Start();
while (true)
{
Console.WriteLine("Waiting for a new Client...");
TcpClient client = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(serviceClient, client);
}
}
catch (Exception e)
{
Console.WriteLine("Server mainline: SocketException: {0}", e);
}
finally
{
server.Stop();
server.Server.Close();
}
}
/// <summary>
/// method to run to handle each client on separate thread
/// </summary>
void serviceClient(object clientObject)
{
Thread currentThread = Thread.CurrentThread;
int threadID = currentThread.GetHashCode();
try
{
using (TcpClient client = (TcpClient)clientObject)
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
Console.WriteLine("Connected with a client, threadID: {0}", threadID);
string option = reader.ReadLine();
while (option != "7")
switch (option)
{
case "1":
case "one":
string[] myfiles = Directory.GetFiles(#"c:\st12_13d1_files");
Console.WriteLine("File Names {0}",Directory.GetFiles
(#"c:\st12_13d1_files"));
foreach (string file in myfiles)
{
//Console.WriteLine(file);
Console.WriteLine(Path.GetFileName(file));
writer.WriteLine(myfiles);
}
break;
}
With all due respect, I don't think it's appropriate to ask others to complete your homework assignments for you.
As a student, it should be your job to research (there are any number of TCP socket demos and tutorials on the web) and experiment with several solutions before resorting to asking others for help.
Software development is as much art as it is science and it requires that you spend time practicing your art. You cannot learn to be a great programmer by reading books and having others do your work for you.
Voting to close.
Update: Not wanting to be a complete curmudgeon, here are some links to some tutorials that should help you really get to grips with async TCP/socket programming:
Learn C# Socket Programming
What is a good tutorial/howto on .net / c# socket programming

List used TCP port using C#

This is the answer to my questions.
How to list binded/used TCP port in C#. Used modified code from jro
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
IPEndPoint TCPInfo = (IPEndPoint)myEnum.Current;
usedPort.Add(TCPInfo.Port);
}
}
Original questions.
This is how i list TCP port using C#. It is modified code i found in this forum(forgot exactly where i got it. If you are the original developer, notify me and ill put credits where due.)
//List used tcp port
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current;
usedPort.Add(TCPInfo.LocalEndPoint.Port);
}
}
Problem is, the results is different from used tcp port listed in TCPview(Protocol-TCP, Local port).
By the way, i do know that this list used TCP port at the EXACT time its called.
What did i did wrong?
I get the same result:
But it does also show listeners (ipGlobalProperties.GetActiveTcpListeners()) which may or may not be closed down.
using your example (with an extra Console.WriteLine in there
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Collections;
namespace ConsoleApplication1 {
static class Program {
//List used tcp port
static void ListAvailableTCPPort(ref ArrayList usedPort) {
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext()) {
TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current;
Console.WriteLine("Port {0} {1} {2} ", TCPInfo.LocalEndPoint, TCPInfo.RemoteEndPoint, TCPInfo.State);
usedPort.Add(TCPInfo.LocalEndPoint.Port);
}
}
public static void Main(){
ArrayList usedPorts = new ArrayList();
ListAvailableTCPPort(ref usedPorts);
Console.ReadKey();
}
}
}
It's a bit of a guess but TCPView probably also shows listener tcp ports (ipGlobalProperties.GetActiveTcpListeners())

Categories

Resources