C# communication with browser using JavaScript - c#

How to pass messages to C# application from JavaScript, I'm able to do this with PHP and tcpListner in c#(but using PHP need server to host), i need localhost communicate c# application with browser(using javaScript or any other possible way), browser need to pass messages to application running on same matchine
can you suggest appropriate method for this with sample

You can do this in the following way.
step 1 : you have to create a Listener. TcpListener class or HttpListener in .net can be used to develop the listener. This code shows how to implement a TCP listener.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
//Author : Kanishka
namespace ServerSocketApp
{
class Server
{
private TcpListener tcpListn = null;
private Thread listenThread = null;
private bool isServerListening = false;
public Server()
{
tcpListn = new TcpListener(IPAddress.Any,8090);
listenThread = new Thread(new ThreadStart(listeningToclients));
this.isServerListening = true;
listenThread.Start();
}
//listener
private void listeningToclients()
{
tcpListn.Start();
Console.WriteLine("Server started!");
Console.WriteLine("Waiting for clients...");
while (this.isServerListening)
{
TcpClient tcpClient = tcpListn.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(handleClient));
clientThread.Start(tcpClient);
}
}
//client handler
private void handleClient(object clientObj)
{
TcpClient client = (TcpClient)clientObj;
Console.WriteLine("Client connected!");
NetworkStream stream = client.GetStream();
ASCIIEncoding asciiEnco = new ASCIIEncoding();
//read data from client
byte[] byteBuffIn = new byte[client.ReceiveBufferSize];
int length = stream.Read(byteBuffIn, 0, client.ReceiveBufferSize);
StringBuilder clientMessage = new StringBuilder("");
clientMessage.Append(asciiEnco.GetString(byteBuffIn));
//write data to client
//byte[] byteBuffOut = asciiEnco.GetBytes("Hello client! \n"+"You said : " + clientMessage.ToString() +"\n Your ID : " + new Random().Next());
//stream.Write(byteBuffOut, 0, byteBuffOut.Length);
//writing data to the client is not required in this case
stream.Flush();
stream.Close();
client.Close(); //close the client
}
public void stopServer()
{
this.isServerListening = false;
Console.WriteLine("Server stoped!");
}
}
}
Step 2 : you can pass parameters to the created server as a GET request. You can use either JavaScript or HTML Forms to pass parameters. JavaScript libraries like jQuery and Dojo will make it easier to make ajax requests.
http://localhost:8090?id=1133
You have to modify the above code to retrieve the parameters send as a GET request.
I recommend to use HttpListener instead of TcpListener
Once you have done with the listening part rest part is just processing the retrieved parameters from the request.

You should use the HttpListener class, or create a self-hosted ASP.Net Web API project.

I think you need a something like Comet, check this example using Comet

Related

Listen to message from an IP from another machine

I am trying to send a message to Unity through UDP. The machine that sends the message has IP as 192.16.14.1 and port as 3034. How do I enter these two inside of Unity application? I have found a code to listen for UDP messages but I cannot set the IP address here. Also the Unity application should be running at all times even if the message from another machine is sent or not.
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
public class UDP_Listen : MonoBehaviour
{
UdpClient clientData;
int portData = 3034;
public int receiveBufferSize = 120000;
public bool showDebug = false;
IPEndPoint ipEndPointData;
private object obj = null;
private System.AsyncCallback AC;
byte[] receivedBytes;
void Start()
{
InitializeUDPListener();
}
public void InitializeUDPListener()
{
ipEndPointData = new IPEndPoint(IPAddress.Any, portData);
clientData = new UdpClient();
clientData.Client.ReceiveBufferSize = receiveBufferSize;
clientData.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
clientData.ExclusiveAddressUse = false;
clientData.EnableBroadcast = true;
clientData.Client.Bind(ipEndPointData);
clientData.DontFragment = true;
if (showDebug) Debug.Log("BufSize: " + clientData.Client.ReceiveBufferSize);
AC = new System.AsyncCallback(ReceivedUDPPacket);
clientData.BeginReceive(AC, obj);
Debug.Log("UDP - Start Receiving..");
}
void ReceivedUDPPacket(System.IAsyncResult result)
{
//stopwatch.Start();
receivedBytes = clientData.EndReceive(result, ref ipEndPointData);
ParsePacket();
clientData.BeginReceive(AC, obj);
//stopwatch.Stop();
//Debug.Log(stopwatch.ElapsedTicks);
//stopwatch.Reset();
} // ReceiveCallBack
void ParsePacket()
{
// work with receivedBytes
Debug.Log("receivedBytes len = " + receivedBytes.Length);
}
void OnDestroy()
{
if (clientData != null)
{
clientData.Close();
}
}
}
If the Unity application is to be receiving the messages constantly, it needs to be something like:
UdpClient listener = new UdpClient(11000);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("192.16.14.1"), 3034);
while (true)
{
byte[] bytes = listener.Receive(ref groupEP);
}
This should read only calls from the specific IP, not sure which port you want the UDPClient to read out from (specified in the UDPClient constructor) but you can set this to whatever you need it to be.
So there are two different things:
You want to define the receiving local port you Bind your socket to
You want to define the expected sending remote ip + port you want to Receive from
Currently you are using the very same one
ipEndPointData = new IPEndPoint(IPAddress.Any, portData);
for both! (Fun fact: As a side effect by using always the same field you basically allow any sender but are then bond to that specific sender from this moment on)
Actually a lot of things you configure there are the default values anyway so here is more or less what I would do
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
public class UDP_Listen : MonoBehaviour
{
public ushort localReceiverPort = 3034;
public string senderIP = "192.168.111.1";
public ushort remoteSenderPort = 3034;
public bool showDebug = false;
// Thread-safe Queue to handle enqueued actions in the Unity main thread
private readonly ConcurrentQueue<Action> mainThreadActions = new ConcurrentQueue<Action>();
private Thread udpListenerThread;
private void Start()
{
// do your things completely asynchronous in a background thread
udpListenerThread = new Thread(UDPListenerThread);
udpListenerThread.Start();
}
private void Update()
{
// in the Unity main thread work off the actions
while (mainThreadActions.TryDequeue(out var action))
{
action?.Invoke();
}
}
private void UDPListenerThread()
{
UdpClient udpClient = null;
try
{
// local end point listens on any local IP
var localEndpoint = new IPEndPoint(IPAddress.Any, localReceiverPort);
udpClient = new UdpClient(localEndpoint);
if (showDebug)
{
Debug.Log("BufSize: " + clientData.Client.ReceiveBufferSize);
}
Debug.Log("UDP - Start Receiving..");
// endless loop -> ok since in a thread and containing blocking call(s)
while (true)
{
// remote sender endpoint -> listens only to specific IP
var expectedSenderEndpoint = new IPEndPoint(IPAddress.Parse(senderIP), remoteSenderPort);
// blocking call - but doesn't matter since this is a thread
var receivedBytes = udpClient.Receive(ref expectedSenderEndpoint);
// parse the bytes here
// do any expensive work while still on a background thread
mainThreadActions.Enqueue(() =>
{
// Put anything in here that is required to happen in the Unity main thread
// so basically anything using GameObject, Transform, etc
});
}
}
// thrown for "Abort"
catch (ThreadAbortException)
{
Debug.Log("UDP Listener terminated");
}
// Catch but Log any other exception
catch (Exception e)
{
Debug.LogException(e);
}
// This is run even if an exception happend
finally
{
// either way dispose the UDP client
udpClient?.Dispose();
}
}
private void OnDestroy()
{
udpListenerThread?.Abort();
}
}
I'm sure the same can be done also using the BeginReceive/EndReceive or task based alternatives but since it is going to run endless anyway I personally find a thread often easier to read and maintain.
I think you got it backwards. This code you shared is for, like you said, listen UDP protocol on desired port. This piece of code needs to be inside your "server". By server try to understand that as the receiving side.
on your shared method InitializeUDPListener(); we have this piece:
ipEndPointData = new IPEndPoint(IPAddress.Any, portData);
this means you are initializing your udp socket to listen for ANY ip adresses at the given port. That said, you have your server ready to go, what you need to do is setup the client side, the one who sends the message.
here some example:
public string serverIp = "127.0.0.1"; // your server ip, this one is sending to local host
public int serverPort = 28500; // your server port
public void ClientSendMessage()
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse(serverIp);
byte[] sendbuf = Encoding.ASCII.GetBytes("THIS IS A MESSAGE FROM CLIENT!");
IPEndPoint ep = new IPEndPoint(broadcast, serverPort);
s.SendTo(sendbuf, ep);
}
I encourage you to read about UDP/TCP protocols before using them. MS has documentation with details.
here some links:
TCP
UDP
Sockets

C# Chat application freezes when code is executed

so I have been working on my chat application in c# as a windows form application and when this code to receive data has to be executed the program freezes.
Anyone help me please, finding out whats wrong about this. As a console application it works.
UdpClient udpClient = new UdpClient(Convert.ToInt32(textPort.Text));
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
textMsg.Text = returnData.ToString();
Your program is frozen because the UdpClient class's Receive(...) method is blocking.
That is to say, it will stop at that point of execution and not allow the thread/process it is in to continue until it receives a single UDP packet. This includes the UI unless you put this in a separate thread or us an asynchronous communication model.
If you want to handle communications asynchronously, check out the BeginReceive(...) method.
And here is some example code (Originally, I was using this codestraight from Microsoft. However, it was missing the definition for UdpState. After some teeth gnashing, I figured out you had to create it to pass your own state in so the asynchronous model would work as expected. The example has been updated and compiles in VS2008, .Net 3.5):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
class UdpState
{
public IPEndPoint e = null;
public UdpClient u = null;
}
class Program
{
public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}
public static void ReceiveMessages(int listenPort)
{
// Receive a message and write it to the console.
IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
UdpClient u = new UdpClient(e);
UdpState s = new UdpState();
s.e = e;
s.u = u;
Console.WriteLine("listening for messages");
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
// Do some work while we wait for a message. For this example,
// we'll just sleep
while (!messageReceived)
{
Thread.Sleep(100);
}
}
static void Main(string[] args)
{
ReceiveMessages(10000);
}
}
}
Was this helpful?
You should investigate how threading works.
In windows forms you could use BackgroundWorker
On msdn you can even find a working sample code.
PS: be sure not to call UI controls directly in the DoWork event (it runs on another thread). If you really need to, invoke it through the Invoke method that exists in every windows forms control.

When to close a UDP socket

I have a client-server application that uses a UDP socket to send the data , the data only have to travel from client to server , and the server will always have the same IP. The only requirement is that I have to send messages about 10 messages per second
Currently I am doing it the following way :
public void SendData(byte[] packet)
{
IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
UdpClient udpChannel = new UdpClient(sourcePort);
udpChannel.Connect(end_point);
udpChannel.Send(packet, packet.Length);
udpChannel.Close();
}
The problem I have is that when I use the command "udpChannel.Close()" it takes 2-3 seconds to be performed when the server is not listening. (I've seen the same problem in: What is the drawback if I do not invoke the UdpClient.Close() method?)
My question would be, if I always send packets to the same IP address and port, is it necessary to connect the socket and close it after each send request?
The code I intend to use would be as follows:
UdpClient udpChannel;
public void SendData(byte[] packet)
{
udpChannel.Send(packet, packet.Length);
}
public void Initialize(IPAddress IP, int port)
{
IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
UdpClient udpChannel = new UdpClient(sourcePort);
udpChannel.Connect(end_point);
}
public void Exit()
{
udpChannel.Close();
}
Doing it this way, would it be necessary to do some checking in the "SendData" method before sending the data?
Is there any problem in the above code?
Thank you!
UDP is connectionless, calling udpChannel.Connect merely specifies a default host endpoint for use with the Send method. You do not need to close the client between sends, leaving it open will not leave any connections or listeners running between sends.
You shouldn't connect/close after each send request. When you start working - you connect to socket. And you can send data. You should close UdpClient when you do not want to send/recieve data, for example when you closing Form.
In your case you can check that udpClient != null when close/send client and you can use try/catch, for example:
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception exc)
{
// handle the error
}
Use try/catch when you connecting, because port may be busy or other problem with connection.
And look at UdpClient.SendAsync :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Net.Sockets;
using System;
using System.Net;
public class Server : MonoBehaviour
{
//int[] ports;
UdpClient udp; // Udp client
private void Start()
{
udp = new UdpClient(1234);
udp.BeginReceive(Receive, null);
}
void Send(string msg, IPEndPoint ipe)
{
UdpClient sC = new UdpClient(0);
byte[] m = Encoding.Unicode.GetBytes(msg);
sC.Send(m, msg.Length * sizeof(char), ipe);
Debug.Log("Sending: " + msg);
sC.Close();
}
void Receive(IAsyncResult ar)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udp.EndReceive(ar, ref ipe);
string msg = Encoding.Unicode.GetString(data);
Debug.Log("Receiving: " + msg);
udp.BeginReceive(Receive, null);
}
}
At the Send() I use new UDP CLient and close it after every time. Its better, u can send and receive at the same time.

Metro app using socketstream to write to Win32 TCPListener in C#

Last year I wrote a home automation application that i could use to control a server from a laptop - the server application used the following resources
using System.Net;
using System.Net.Sockets;
using System.IO;
And then created TCPListener to recieve commands from a local network.
TcpListener server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
then processing the stream for correct command and parameters and this worked ok for both the client and server.
I started writing a metro app for the remote control, and because of this, I've had to use
using Windows.Networking.Sockets;
using Windows.Networking;
Then created an async void to send the command. (sorry this is very messy)
async void sendTest()
{
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName("192.168.88.1"), "13000",SocketProtectionLevel.PlainSocket);
DataWriter writer;
writer = new DataWriter(socket.OutputStream);
// Write first the length of the string as UINT32 value followed up by the string. Writing data to the writer will just store data in memory.
string stringToSend = "Hello";
writer.WriteUInt32(writer.MeasureString(stringToSend));
writer.WriteString(stringToSend);
await writer.StoreAsync();
}
I get an exception (no response in the timeout period)
I know my server is not giving a response, but i've tried a number of things such as AcceptSocket, however these still don't detect that the client has connected.
I'm wondering if Metro has another network library that I can use, or whether someone can suggest an alternative code for my server Listener.
Thanks in advance
Is seems you are looking for a StreamSocketListener. What about this?
private StreamSocketListener listener;
private async void Test()
{
listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
await listener.BindServiceNameAsync(port.ToString());
}
private async void OnConnection(StreamSocketListener sender,
StreamSocketListenerConnectionReceivedEventArgs args)
{
// Streams for reading a writing.
DataReader reader = new DataReader(listener.InputStream);
DataWriter writer = new DataWriter(socket.OutputStream);
writer.WriteString("Hello");
await writer.StoreAsync();
}

Communication from C# Application to Firefox Extension

I need to send some strings (name, number) from my C# application to my Firefox Extension and i have read some techniques of doing but no idea how to implement it.
Pipes
Sockets(HTTP request)
If its using HTTP Request its better.
UPDATE
onSocketAccepted : function(socket, transport)
{
alert("came")
var input =transport.openInputStream(0, 0, 0);
alert(input)
}
does the message i send from the C# application will be in var input???
In C# Side DO
using System.Net;
using System.Net.Sockets;
static Socket sck;
acceptClient(String str)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 777);
try
{
sck.Connect(localEndPoint);
string text = str;
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
// MessageBox.Show("Data Sent!\r\n");
}
catch
{
MessageBox.Show("Unable to connect to remote end point!\r\n");
}
}
In the Extension DO
function startServer()
{
var reader =
{
onInputStreamReady : function(input) {
var sin = Cc["#mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
sin.init(input);
sin.available();
//alert('count:'+count)
var request = '';
vaulee='';
while (sin.available()) {
request = request + sin.read(5120);
}
careditcardnum=request;
//alert(request)
input.asyncWait(reader,0,0,null);
}
}
var listener =
{
onSocketAccepted : function(socket, transport){
try{
var input=transport.openInputStream(0,0,0).QueryInterface(Ci.nsIAsyncInputStream);
var output = transport.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
var tm = Cc["#mozilla.org/thread-manager;1"].getService();
input.asyncWait(reader,0,0,tm.mainThread);
//stream.close();
} catch(ex2){ dump("::"+ex2); }
},
onStopListening : function(socket, status){
}
};
try {
serverSocket = Components.classes["#mozilla.org/network/server-socket;1"]
.createInstance(Components.interfaces.nsIServerSocket);
serverSocket.init(777,true,-1);
serverSocket.asyncListen(listener);
} catch(ex){ dump(ex); }
}
It's easiest to use TCP sockets. Firefox add-ons can run TCP servers using nsIServerSocket. You can see a pretty simple server implementation here (belongs to the Extension Auto-Installer extension). This isn't an HTTP server - it merely throws away whatever it considers HTTP headers without looking at them. There is also a full HTTP server implementation that's being used for Firefox unit tests - but you probably don't want it that complicated.
You could try SignalR.
https://github.com/SignalR/SignalR

Categories