Send an ASCII message - c#

I have a "Sysmex XP-300" machine who sends data via TCP, I need to catch this data and reply with ASCII, to verify that the it was received.
The problem is, that every time the machine is connected, the code will reply "connected" non stop. I also need to reply with ASCII that my machine seems not receive. Here my code:
class Program
{
static string ack = char.ConvertFromUtf32(6);
byte[] byData = System.Text.Encoding.ASCII.GetBytes(ack);
const int PORT_NO = 3001;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
TcpServer tcpServer = new TcpServer(SERVER_IP, 3001);
tcpServer.Connected += new TcpServer.TcpServerEventDlgt(OnConnected);
tcpServer.StartListening();
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
tcpServer.StopListening();
}
static void OnConnected(object sender, TcpServerEventArgs e)
{
// Handle the connection here by starting your own worker thread
// that handles communicating with the client.
Console.WriteLine("Connected.");
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(ack);// ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " );
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}

Related

Real server-client C# program over internet

Simple question, but after weeks of search no luck. I need to create a server-client program. Everything works well with localhost, but I need it over the internet. I work under Linux (Ubuntu).
Server:
public class SocketServer
{
private const int PORT_NO = 8001;
public SocketServer()
{
//---listen at the specified IP and port no.---
var listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Socket server started.");
listener.Start();
while (true)
{
//---incoming client connected---
var client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
var nwStream = client.GetStream();
var buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
var bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"{dataReceived}");
client.Close();
}
}
}
Client code:
public class Client
{
private const int PORT_NO = 8001;
private const string SERVER_IP = "xxx.xx.246.1";
public void Run()
{
while (true)
{
var textToSend = Console.ReadLine();
//---create a TCPClient object at the IP and port no.---
var client = new TcpClient(SERVER_IP, PORT_NO);
var nwStream = client.GetStream();
var bytesToSend = Encoding.ASCII.GetBytes(textToSend ?? string.Empty);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
For IP I used www.whatsmyip.org, and I got an error:
System.Net.Sockets.SocketException (0x80004005): Connection refused
What am I missing? Is there some real example, no just with localhost?

Keep TcpListerner in Idle state C#

i have these code for a server and client program. client program sends a value to server and server reads it. but here after first message, server shuts down.
i want it to be listerning until the full application shuts down. so after 1 connection closes, it will wait for next connection and so on.
internal static async Task ServerHandler()
{
Console.Writeline("starting server...");
IPAddress b = IPAddress.Any;
TcpListener Server = new TcpListener(b, 5550);
Server.Start();
Console.Writeline("Server Started Sucessfully!");
Console.Writeline("Waiting for Connection...");
TcpClient Client = Server.AcceptTcpClient();
string clientIPAddress = "Connected! => " + IPAddress.Parse(((IPEndPoint)Client.Client.RemoteEndPoint).Address.ToString());
Console.Writeline(clientIPAddress);
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
try
{
Stream MessageStream = Client.GetStream();
bytesRead = MessageStream.Read(message, 0, 4096);
ASCIIEncoding encoder = new ASCIIEncoding();
string recivedMessage = encoder.GetString(message, 0, bytesRead);
Console.Writeline(recivedMessage);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Client.Close();
Server.Stop();
}
}

TCPlistener server-client and client-server ( send message to client from server)

All i want to do is send message to client from server. I try a lot of tutorial etc. but still can't send message from server to client.
Send from client to server is simple and have it in code. When client Send "HI" to server i want to respond Hi to client. But dunno what should i add to my code. Can someone help me with that? Please don't do it like duplicate i know there is a lot of similar topic but can't find solution.
Server code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener server = new TcpListener(ip, Convert.ToInt32(8555));
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
};
while (true)
{
client = server.AcceptTcpClient();
byte[] receivetBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivetBuffer, 0, receivetBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach(byte b in receivetBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
////Resive message :
if (msg.ToString() =="HI")
{
///#EDIT 1
///// HERE Is SENDING MESSAGE TO CLIENT//////////
int byteCount = Encoding.ASCII.GetByteCount("You said HI" + 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("You said HI" + ";");
stream.Write(sendData, 0, sendData.Length);
}
}
Client code:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string serverIP = "localhost";
int port = Convert.ToInt32(8555);
TcpClient client = new TcpClient(serverIP, port);
int byteCount = Encoding.ASCII.GetByteCount("HI"+ 1);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes("HI" + ";");
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
///////////////////////////////HERE I WANT A read message from server/
/////////////////////////////////////////////////////////////////////
stream.Close();
client.Close();
}
catch(Exception ex)
{
ex.ToString();
}
}
Try this Here is my version of client and server ,feel free to ask if any reference problem ,the client wait for server to (online) then if server is online connect with it.
Method to Connect with Server
private void Connectwithserver(ref TcpClient client)
{
try
{
//this is server ip and server listen port
server = new TcpClient("192.168.100.7", 8080);
}
catch (SocketException ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
RunBoTClient();
}
}
byte[] data = new byte[1024];
string stringData;
TcpClient client;
private void RunClient()
{
NetworkStream ns;
Connectwithserver(ref client);
while (true)
{
ns = client.GetStream();
//old
// ns.ReadTimeout = 50000;
//old
ns.ReadTimeout = 50000;
ns.WriteTimeout = 50000;
int recv = default(int);
try
{
recv = ns.Read(data, 0, data.Length);
}
catch (Exception ex)
{
//exceptionsobj.WriteException(ex);
Thread.Sleep(TimeSpan.FromSeconds(10));
//try to reconnect if server not respond
RunClient();
}
//READ SERVER RESPONSE/MESSAGE
stringData = Encoding.ASCII.GetString(data, 0, recv);
}
}
Server
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//IF YOU WANT TO WRITE BACK TO CLIENT USE
string yourmessage = console.ReadLine();
Byte[] sendBytes = Encoding.ASCII.GetBytes(yourmessage);
//---write back the text to the client---
Console.WriteLine("Sending back : " + yourmessage );
nwStream.Write(sendBytes, 0, sendBytes.Length);
client.Close();
}
listener.Stop();

Acknowledgement didn't work..Teltonika FM5300

Here is a sample of my code. It doesn't work. I sent acknowledgement in the right form {0x01} but the device always returns only IMEI. Could someone solve this problem?
static void Main(string[] args)
{
TcpListener list = new TcpListener(new IPEndPoint(IPAddress.Any, 2065));
TcpClient client;
Console.WriteLine("Listening... \n");
list.Start(1);
list.Server.NoDelay = true;
while (true)
{
Console.WriteLine("Waiting for client...\n");
client = list.AcceptTcpClient();
Console.WriteLine("Client connected ");
byte[] imei = new byte[8192];
NetworkStream ns = client.GetStream();
if (ns.CanRead)
{
ns.Read(imei, 0, (int)client.ReceiveBufferSize);
}
Console.WriteLine(Encoding.ASCII.GetString(imei, 0, imei.Length));
byte[] ack = new byte[1] {0x01};
if (ns.CanWrite)
{
ns.Write(ack, 0, ack.Length);
}
client.Close();
}
}
Like Ron said, you keep sending the same thing over and over. After you receive IMEI, your code sends correct response and disconnects. So next connection starts from beginning, with IMEI... The data from device comes over the same connection, so... why disconnect? ;)
– mlask

Send TCP data to specfic TcpClient in C#

I'm getting an error that the TcpClient isn't connected and I can't send information to a socket that is not active. I'm wondering what's wrong with this code?
ERROR: This type of connection is not allowed on non-connected sockets.
SERVER:
public List<TcpClient> clients = new List<TcpClient>();
On client connection:
Socket s = currClient.Client;
clients.Add(currClient.Client);
When Sending Client Info
Stream sendData = clients[0].GetStream();
ASCIIEncoding text = new ASCIIEncoding();
byte[] clientInfoByte = text.GetBytes("msg");
sendData.Write(clientInfoByte, 0, clientInfoByte.Length);
sendData.Close();
CLIENT:
Thread thr = new Thread(commands);
thr.Start();
}
public static void commands()
{
Stream cmds = me.GetStream();
while (true)
{
byte[] b = new byte[100];
Socket s = me.Client;
int k = s.Receive(b);
string ClientInfo = "";
string command = System.Text.Encoding.ASCII.GetString(b);
if (command == "msg")
{
MessageBox.Show("Command Recieved!");
}
}
}
In your server create a TcpListener "listener" and accept incoming connections using:
listener.BeginAcceptTcpClient(
new AsyncCallback(DoAcceptTcpClientCallback),
listener);
Then in your callback you get your TcpClient to send data to
// Process the client connection.
public static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener) ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
//add to your client list
clients.Add(client);
}

Categories