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
Related
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
My application requires a user to select a SQL Server instance on their network to serve as the app's database server. I need to populate a list of all available SQL Server instances from which to make this selection.
The application is developed in .NET Core 3.1. I am unable to simply use SqlDataSourceEnumerator as it is not available in .NET Core.
Is there an alternative available to make this query?
I'd like to avoid importing PowerShell functionality to the application if possible, as it would likely require additional PowerShell modules to be installed on the machine, but will consider it if it's the only way.
The only way I've found to do this in .NET Core is to manually send and receive UDP messages.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using ReporterAPI.Utilities.ExtensionMethods;
using Serilog;
public class SqlServerScanner : ISqlServerScanner
{
private readonly ConcurrentDictionary<string, SqlServerInstance> serverInstances = new ConcurrentDictionary<string, SqlServerInstance>();
private DateTime lastScanAttemptTime = DateTime.MinValue;
private readonly TimeSpan cacheValidTimeSpan = TimeSpan.FromSeconds(15);
private readonly TimeSpan responseTimeout = TimeSpan.FromSeconds(2);
private readonly List<UdpClient> listenSockets = new List<UdpClient>();
private readonly int SqlBrowserPort = 1434; // Port SQL Server Browser service listens on.
private const string ServerName = "ServerName";
public IEnumerable<SqlServerInstance> GetList()
{
ScanServers();
return serverInstances.Values;
}
private void ScanServers()
{
lock (serverInstances)
{
if ((DateTime.Now - lastScanAttemptTime) < cacheValidTimeSpan)
{
Log.Debug("Using cached SQL Server instance list");
return;
}
lastScanAttemptTime = DateTime.Now;
serverInstances.Clear();
try
{
var networksInterfaces = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
foreach (var networkInterface in networksInterfaces.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork))
{
Log.Debug("Setting up an SQL Browser listen socket for {address}", networkInterface);
var socket = new UdpClient { ExclusiveAddressUse = false };
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.Client.Bind(new IPEndPoint(networkInterface, 0));
socket.BeginReceive(new AsyncCallback(ResponseCallback), socket);
listenSockets.Add(socket);
Log.Debug("Sending message to all SQL Browser instances from {address}", networkInterface);
using var broadcastSocket = new UdpClient { ExclusiveAddressUse = false };
broadcastSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
broadcastSocket.Client.Bind(new IPEndPoint(networkInterface, ((IPEndPoint)socket.Client.LocalEndPoint).Port));
var bytes = new byte[] { 0x02, 0x00, 0x00 };
broadcastSocket.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Broadcast, SqlBrowserPort));
}
Thread.Sleep(responseTimeout);
foreach (var socket in listenSockets)
{
socket.Close();
socket.Dispose();
}
listenSockets.Clear();
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to initiate SQL Server browser scan");
throw;
}
}
}
private void ResponseCallback(IAsyncResult asyncResult)
{
try
{
var socket = asyncResult.AsyncState as UdpClient;
var localEndpoint = socket.Client.LocalEndPoint as IPEndPoint;
var bytes = socket.EndReceive(asyncResult, ref localEndpoint);
socket.BeginReceive(new AsyncCallback(ResponseCallback), socket);
if (bytes.Length == 0)
{
Log.Warning("Received nothing from SQL Server browser");
return;
}
var response = System.Text.Encoding.UTF8.GetString(bytes);
Log.Debug("Found SQL Server instance(s): {data}", response);
foreach (var instance in ParseInstancesString(response))
{
serverInstances.TryAdd(instance.FullName(), instance);
}
}
catch (Exception ex) when (ex is NullReferenceException || ex is ObjectDisposedException)
{
Log.Debug("SQL Browser response received after preset timeout {timeout}", responseTimeout);
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to process SQL Browser response");
}
}
/// <summary>
/// Parses the response string into <see cref="SqlServerInstance"/> objects.
/// A single server may have multiple named instances
/// </summary>
/// <param name="serverInstances">The raw string received from the Browser service</param>
/// <returns></returns>
static private IEnumerable<SqlServerInstance> ParseInstancesString(string serverInstances)
{
if (!serverInstances.EndsWith(";;")
{
Log.Debug("Instances string unexpectedly terminates");
yield break;
}
// Remove cruft from instances string.
var firstRecord = serverInstances.IndexOf(ServerName);
serverInstances = serverInstances[firstRecord..^2];
foreach (var instance in serverInstances.Split(";;"))
{
var instanceData = instance.Split(";");
yield return new SqlServerInstance
{
ServerName = instanceData[1],
InstanceName = instanceData[3],
IsClustered = instanceData[5].Equals("Yes"),
Version = instanceData[7]
};
}
}
}
This seems faster than the old SMO EnumerateServers method, probably because it doesn't test each instance for connectivity, which I kind of like. I want to know what servers are out there, even if I have to fix something before being able to actually connect.
This function sends from a randomly selected UDP port, so be aware of the need for a firewall rule to allow traffic for the executable, but you can limit to remote port 1434.
The accepted answer is incomplete (misses one class) and uses some unexplained variables like "ServerName" (assumably, the local server name? And what is "remove cruft"?)
Anyway, I found this version way better: https://stackoverflow.com/a/64980148/56621
(also a UDP scanner that works on NET Core)
I am using a UDP socket to send eventlog data to a log analysis server, and don't want to block threads unnecessarily. The sending application is a Windows background service using a default threadpool.
// Should this be async? It's UDP only...
public static void LogUDP(string message)
{
try
{
var hostname = ConfigurationManager.AppSettings.Get<string>("SyslogUDPHostName", string.Empty);
var portString = ConfigurationManager.AppSettings.Get<string>("SyslogUDPHostPort", string.Empty);
var port = Convert.ToInt32(portString);
var ipParse = System.Net.Dns.GetHostAddresses(hostname);
var ip = ipParse.First();
// Create Endpoint
var udpEndpoint = new System.Net.IPEndPoint(ip, port);
// Create Socket
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Ttl = 26;
// Connect the socket
socket.Connect(udpEndpoint);
// Create the encoded buffer
var buffer = System.Text.Encoding.ASCII.GetBytes(message);
// Send the buffer
var sent = socket.Send(buffer);
}
catch (Exception ex)
{
}
}
Is it necessary or recommended to use Async for UDP based outbound-only messages?
I'm looking through the sample Microsoft-provided code to learn how to write equivalent Async code, but not sure if it's needed. My doubt is reaffirmed when I look at the overloads for BeginSend and every method has an AsyncCallback, and in the case of UDP, I'm not sure what to put there (null?)?
Advice welcome.
I'm trying to make a IP version-agnostic client/server. I've been playing around with this in C++ and came up with something that works using the IN6ADDR_SETV4MAPPED macro (as Microsoft so kindly recommends). I followed the code sample here to accomplish this; my code that converts the address is no different from the example and everything works. I can connect to the server from the client by typing in both an IPv4 and IPv6 address (application does the mapping accordingly).
Now I'm looking for a solution in C# to upgrade a simple chat server I made and I've been unable to find any resources on how to use mapped addresses. I haven't found a function that provides the equivalent of IN6ADDR_SETV4MAPPED or any other facility in .net. My question is: how can I go about using a IPv4-mapped IPv6 address in C# (client-side)?
What I've tried:
Prepend string "::ffff:" to dotted IPv4 notation, call Socket.Connect using this address. Resulting address string looks like ::ffff:127.0.0.1.
Prepend string "::ffff:". Convert each octect from dotted format into hex and separate with colons, call Socket.Connect. Resulting address string looks like ::ffff:7f:0:0:1.
Neither of these approaches have worked so far.
Code snippet for server:
this.m_endPoint = new IPEndPoint(IPAddress.IPv6Any, 1337);
this.m_server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
this.m_server.Bind(this.m_endPoint);
this.m_server.Listen(10);
Code snippet for client:
public ClientNet(string host, short port)
{
IPAddress ip;
if(IPAddress.TryParse(host, out ip))
{
string[] octs = host.Split(new char[] { '.' });
host = "::ffff:";
for(int i = 0; i < octs.Length; ++i)
{
host += string.Format("{0:x}", int.Parse(octs[i]));
if(i + 1 != octs.Length)
{
host += ":";
}
}
}
else
{
throw new ClientCreateException("[in ClientNet.Constructor] Unable to create client; use IPv4 address");
}
Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
client.Connect(host, port);
. . . //More initialization
}
Came back to this today thinking I might be able to figure it out. And I did! The answer is quite easy and I feel like a fool for not getting it for a year.
Two things about the code I posted:
Should have used IPAddress.MaptoIPv6 (see MSDN link) instead of that silly, contrived loop I wrote that's more prone to errors.
a. I realized later while working in .NET 4.0 that the convenience functions I used in my sample are not available until .NET 4.5. A quick code sample I threw together is at the bottom of this post, in case anyone else is stuck in an earlier version of .NET.
Real solution: Needed to call client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0); prior to calling client.Connect().
Here is a full code example of a sample application I wrote today to test it out. I was able to make a connection using both ::1 and 127.0.0.1 as addresses. Note that the server Socket is created for IPv6, and that the SocketOptionName.IPv6Only option is set to 0 on both the client and the server.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace sixsharp
{
class Program
{
static void Main(string[] args)
{
if(args.Length <= 0) //run as server
RunServer();
else
RunClient(args);
Console.WriteLine("Press enter to close.");
Console.ReadLine();
}
static void RunServer()
{
using(Socket serv = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
serv.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
serv.Bind(new IPEndPoint(IPAddress.IPv6Any, 1337));
serv.Listen(5);
Console.Write("Listening for client connection...");
using(Socket client = serv.Accept())
{
Console.WriteLine("Client connection accepted from {0}", client.RemoteEndPoint.ToString());
byte[] buf = new byte[128];
client.Receive(buf, 128, SocketFlags.None);
Console.WriteLine("Got \'{0}\' from client", Encoding.ASCII.GetString(buf));
Console.WriteLine("Echoing response");
client.Send(buf);
client.Shutdown(SocketShutdown.Both);
}
}
Console.WriteLine("Done.");
}
static void RunClient(string[] args)
{
using(Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
Console.WriteLine("Setting up address, input is {0}", args[0]);
IPEndPoint ep;
try
{
ep = new IPEndPoint(IPAddress.Parse(args[0]), 1337);
}
catch(FormatException fe)
{
Console.WriteLine("IP address was improperly formatted and not parsed.");
Console.WriteLine("Detail: {0}", fe.Message);
return;
}
if(ep.AddressFamily == AddressFamily.InterNetwork)
{
ep = new IPEndPoint(ep.Address.MapToIPv6(), ep.Port);
if(!ep.Address.IsIPv4MappedToIPv6 || ep.Address.AddressFamily != AddressFamily.InterNetworkV6)
{
Console.WriteLine("Error mapping IPv4 address to IPv6");
return;
}
}
Console.WriteLine("Connecting to server {0} ...", ep.ToString());
try
{
client.Connect(ep);
}
catch(Exception ex)
{
Console.WriteLine("Unable to connect.\n Detail: {0}", ex.Message);
return;
}
client.Send(Encoding.ASCII.GetBytes("This is a test message. Hello!"));
byte[] buf = new byte[128];
client.Receive(buf);
Console.WriteLine("Got back from server: {0}", Encoding.ASCII.GetString(buf));
client.Shutdown(SocketShutdown.Both);
}
Console.WriteLine("Done.");
}
}
}
Client output:
Setting up address, input is 10.2.6.179
Connecting to server [::ffff:10.2.6.179]:1337 ...
Got back from server: This is a test message. Hello!
Done.
Press enter to close.
Server output:
Listening for client connection...Client connection accepted from [::ffff:10.2.6.179]:56275
Got 'This is a test message. Hello!
' from client
Echoing response
Done.
Press enter to close.
Sample extension methods providing the missing convenience functions in earlier versions of .NET:
static class IPAddressExtensions
{
public static IPAddress MapToIPv6(this IPAddress addr)
{
if(addr.AddressFamily != AddressFamily.InterNetwork)
throw new ArgumentException("Must pass an IPv4 address to MapToIPv6");
string ipv4str = addr.ToString();
return IPAddress.Parse("::ffff:" + ipv4str);
}
public static bool IsIPv4MappedToIPv6(this IPAddress addr)
{
bool pass1 = addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6, pass2;
try
{
pass2 = (addr.ToString().StartsWith("0000:0000:0000:0000:0000:ffff:") ||
addr.ToString().StartsWith("0:0:0:0:0:ffff:") ||
addr.ToString().StartsWith("::ffff:")) &&
IPAddress.Parse(addr.ToString().Substring(addr.ToString().LastIndexOf(":") + 1)).AddressFamily == AddressFamily.InterNetwork;
}
catch
{
return false;
}
return pass1 && pass2;
}
}
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