I am trying to receive a message from TcpClient but I am a beginner in C# and have a problem and I don't have good knowledge on how it exactly works!
So the problem is that when I try to receive the message in my computer and run the Tcplistener and the TcpClient, I get the message but if I tried to run the TcpClient on a different computer, it doesn't connect it and log that it's refusing
TcpClient code:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpClient
{
static void Main()
{
Connect("127.0.0.1", "Hello");
}
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.Beep();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Received: {0}", responseData);
Console.ForegroundColor = ConsoleColor.White;
// 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();
}
}
The TcpListener code:
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 use 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.
Console.WriteLine("What should i send for them?");
data = Console.ReadLine();
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();
}
}
Related
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)
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
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.
I'm developing a client-server application, where the client is in Android and the server in C#. Before using C# for the server I used autoIT and it worked fine aside from the fact that I had to send messages of 9 characters or else it would get weird symbols.
Now in C# I'm having the same problem. I tried removing all white space but it always leaves something at the start of the message.
Single word messages like:
"SendClose"
the server reads as
" SendClose" or " SendClose" if i remove the white spaces
Note the leading white space. It's interesting because when I check the string length it says it is only 11 characters so I don't know what is going on; maybe 2 tabs?
Here's my C# code:
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class TcpListenerSample {
static void Main(string[] args) {
try {
// set the TcpListener on port 13000
int port = 80;
IPAddress localAddr = IPAddress.Parse("192.168.1.68");
TcpListener server = new TcpListener(localAddr, 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();
}
}
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(StripExtended(data));
static string StripExtended(string arg)
{
StringBuilder buffer = new StringBuilder(arg.Length); //Max length
foreach(char ch in arg)
{
UInt16 num = Convert.ToUInt16(ch);//In .NET, chars are UTF-16
//The basic characters have the same code points as ASCII, and the extended characters are bigger
if((num >= 32u) && (num <= 126u)) buffer.Append(ch);
}
return buffer.ToString();
}
}
}
I work on Asterisk ami with node.js server
I want to send data from [node.js server] to C# client in real time
server.js
var app = require('http').createServer().listen(3001);
var io = require('socket.io').listen(app);
var AsteriskAmi = require('asterisk-ami');
var ami = new AsteriskAmi( { host: '127.0.0.1', username: 'admin', password: '123456' } );
io.sockets.on('connection', function(socket) {
socket.emit('notification', {message: "connected"});
});
ami.on('ami_data', function(data) {
io.sockets.emit('ami_event', data);
// or the same
// io.emit('ami_event', data);
});
ami.connect(function(){
});
C# sharp client
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 = 3001;
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();
}
}