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();
}
}
Related
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();
}
}
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)
Im writing a Client Server Socket C# with TCP protocoll to create sort of "Client Ask, Server Answer" But when I Execute first command my client close. I should put while somewhere but I don't know where. here is the code:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Now If you copy paste this code and execute Server and then Client, you can write something into CLient prompt and get an answers but at 2 attempt CLient close because there is no while that continues the process! I tried put while out of try and into but code crashed! An Help would be appreciate an help or solution is the same, just get an answer :)
Thank you everyone
I have limited knowledge working with sockets. However I know you should only call the following once:
Socket handler = listener.Accept();
I added a while loop under the above line and also removed your break statements at the end of your if conditions.
So the new code becomes:
CLIENT
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
while (true)
{
Console.WriteLine("Insert text to send to server");
String a = Console.ReadLine(); //This is a test<EOF>
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(a);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
// Release the socket.
//sender.Shutdown(SocketShutdown.Both);
//sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
//To avoid Prompt disappear
Console.Read();
return 0;
}
}
SERVER
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
while (true)
{
try
{
//if (!listener.IsBound)
//{
listener.Bind(localEndPoint);
//}
listener.Listen(10);
byte[] msg = null;
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
while (true)
{
data = null;
// An incoming connection needs to be processed.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.Equals("ping"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes("pong");
handler.Send(msg);
//break;
}
if (data.Equals("dir"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
handler.Send(msg);
//break;
}
if (data.Equals("files"))
{
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
String files = "";
string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
foreach (string fileName in fileEntries)
files += ProcessFile(fileName);
// Echo the data back to the client.
msg = Encoding.ASCII.GetBytes(files);
handler.Send(msg);
//break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static String ProcessFile(string path)
{
return path += "\n\n" + path;
}
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
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 am working on a project where I am going to create a TCP/IP Chat application and I have some problems with passing variables between the classes. The variable data does not get passed on from the handleClient to the main class where data along with clientSocket is saved to a Hashtable. The Hashtable is later going to be used for broadcasting the message to all clients. The error i get is as follows: "Error: The name 'data' does not exist in the current context"
Serverside code:
using System;
using System.IO;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections;
namespace Chat_server
{
public class Program
{
//Creates a list with all clients
public static Hashtable clientList = new Hashtable();
public void Main(string[] args)
{
TcpListener serverSocket = null;
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
serverSocket = new TcpListener(localAddr, port);
// Start listening for client requests.
serverSocket.Start();
int counter = 0;
while (true)
{
counter += 1;
Console.WriteLine("Waiting for a connection... ");
TcpClient clientSocket = serverSocket.AcceptTcpClient();
clientList.Add(data, clientSocket);
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClient hclient = new handleClient();
hclient.startClient(clientSocket);
}
}
}
}
//Class to handle each connection separatly
public class handleClient
{
TcpClient clientSocket;
Hashtable clientList;
public void startClient(TcpClient inClient)
{
this.clientSocket = inClient;
Thread clientThread = new Thread(new ThreadStart(doChat));
clientThread.Start();
}
public void doChat()
{
Byte[] bytes = new Byte[10025];
String data = null;
data = null;
while ((true))
{
try
{
foreach (DictionaryEntry Item in clientList)
{
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clientSocket.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);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
stream.Flush();
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
clientSocket.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
}
}
}
}
data isn't defined in that function or in the class at:
clientList.Add(data, clientSocket);