I've created a small app to get http/https responses:
public static void Listener1(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Seu ambiente não suporta os recursos da classe HttpListener.");
return;
}
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Hello world </BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();
}
And I'm using this prefixes:
string[] url = { "http://localhost:5324/", "https://localhost:5325/" };
When I type http://localhost:5324/ on Chrome, I get the right response, but when using https://localhost:5325/, nothing happens. Not even errors about certificates.
Related
I have two projects: client and server.
Server code:
static void Main()
{
var listener = new TcpListener(System.Net.IPAddress.Loopback, 13000);
listener.Start();
using (var client = listener.AcceptTcpClient())
{
var stream = client.GetStream();
var textStream = new StreamReader(stream);
while (true)
{
var line = textStream.ReadLine();
if (line == "") continue;
if (line == null) continue;
var clientIp = IPAddress.Parse(line.Split(':').First());
var clientPort = int.Parse(line.Split(':').Last());
var response = new LobbyConnectionResponse(StatusCode.OK, "Connected", new List<Player>(), new Leader("J", Guid.NewGuid()));
SendResponseToClient(clientIp, clientPort, response);
Console.WriteLine(line);
Thread.Sleep(lobbyResponseTimeout);
}
}
listener.Stop();
}
static Task SendResponseToClient(IPAddress ip, int port, LobbyConnectionResponse response)
{
var task = Task.Run(() =>
{
using (var tcpClient = new TcpClient())
{
tcpClient.Connect(ip, port);
var stream = tcpClient.GetStream();
var textStream = new StreamWriter(stream);
string jsonString = JsonSerializer.Serialize(response);
textStream.WriteAsync(jsonString);
stream.FlushAsync();
}
});
return task;
}
Client code:
static void Main()
{
StartListener();
using (var client = new TcpClient())
{
client.Connect("127.0.0.1", 13000);
var stream = client.GetStream();
var textStream = new StreamWriter(stream);
textStream.WriteLine("127.0.0.1:12000");
textStream.Flush();
}
while(true)
Thread.Sleep(1000);
Thread.Sleep(1000);
}
static Task StartListener()
{
var task = Task.Run(() =>
{
var listener = new TcpListener(System.Net.IPAddress.Loopback, 12000);
listener.Start();
while (true)
{
using (var client = listener.AcceptTcpClient())
{
var stream = client.GetStream();
var textStream = new StreamReader(stream);
while (true)
{
if (stream.DataAvailable)
Console.WriteLine("hfdsgdf");
var line = textStream.ReadLine();
if (line == null || line == "") continue;
var response = (LobbyConnectionResponse)JsonSerializer.Deserialize(stream, typeof(LobbyConnectionResponse));
Console.WriteLine(response.Description);
Thread.Sleep(100);
}
}
Thread.Sleep(100);
}
listener.Stop();
});
return task;
}
On the server's console, I had message:"127.0.0.1:12000" but client's console are empty, why client doesn't receive my text data? 0 Exceptions, clients code just looping infinity and every iteration continues because line == null
When I tried to make that on a single port ( server and client), nothing worked. I want that client get my JSON and deserialize it into class instance.
You need to send data through client/stream variable instead of creating a new connection from server to client.
var listener = new TcpListener(System.Net.IPAddress.Loopback, 13000);
listener.Start();
using (var client = listener.AcceptTcpClient())
{
var stream = client.GetStream();
// send response to client
byte[] buffer = Encoding.UTF8.GetBytes("foo");
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
I have created a function (ListenForJson) in which I am using HttpListener to get requests and send responses from/to a specific address. I am calling this function inside ActionResult Index() so that it can run in the background. However, since I am calling it in the Homepage of my Webapp, whenever I click on the "Go to Home" button I receive an error the error
Failed to listen on prefix because it conficts with an existing registration on the machine
I understand the reason it happens but I do not know how I can stop it from happening.
public ActionResult Index()
{
Thread thread = new Thread(() => ListenForJson());
thread.Start();
return View();
}
public void ListenForJson()
{
string[] prefixes = new string[] { "https://localhost:44337/" };
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
listener.Prefixes.Add(s);
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
//Get Body(Json)
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string json = reader.ReadToEnd();
JsonObject = DeserializeJson(json);
HttpListenerResponse response = context.Response;
var responseJson = JsonSerialization("SERVICE");
byte[] buffer = new byte[] { };
response.ContentType = "Application/json";
buffer = Encoding.ASCII.GetBytes(responseJson);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
context.Response.Close();
}
}
My needs are to send just a simple string. Which method is more right to use, or faster with better performance.
HttpListener
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening..");
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Test </BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();
TcpListener
IPAddress ipAd = IPAddress.Parse("172.21.5.99");
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Socket s=myList.AcceptSocket();
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
s.Close();
myList.Stop();
I need to send from my client a string with some values, example Name=xxx,Age=xxx
,then server to take this string and answering with an "OK"
I have the following HTTP listener method, greatly inspired by MSDN's example use of the HttpListener class. I'm fairly new to programming and I'm not sure where to go from here to initialize it from my Main(). Any suggestions?
public static void HttpListener(string[] prefixes)
{
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("Prefixes needed");
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening..");
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Test </BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();
}
You seem to have removed the comments that are mentioned on the MSDN HttpListener Class page:
// URI prefixes are required, for example "http://contoso.com:8080/index/".
So just call it like that:
public static void Main(string[] args)
{
HttpListener(new[] { "http://localhost/" });
}
But please note this example will handle only one request and then exit. If your follow-up question is then "How can I make it handle multiple requests?", see Handling multiple requests with C# HttpListener.
you can do something like this :
public void ListenTraces()
{
httpListener.Prefixes.Add(PORT_HOST);
try
{
httpListener.Start();
}
catch (HttpListenerException hlex)
{
log.Warn("Can't start the agent to listen transaction" + hlex);
return;
}
log.Info("Now ready to receive traces...");
while (true)
{
var context = httpListener.GetContext(); // get te context
log.Info("New trace connexion incoming");
Console.WriteLine(context.SomethingYouWant);
}
}
I am creating a simple HTTP client/server application on my local machine but I don't know why the ListenerCallback is triggered on the server; however, EndGetContext is not completing while throwing 'Web Exception: Unable to connect to remove server" on the client side. Any ideas? here's the code
class Server
{
static void Main(string[] args)
{
NonblockingListener(new string[] {"http://192.168.0.55:5432/"});
}
public static void NonblockingListener(string[] prefixes)
{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
Console.WriteLine("Waiting for request to be processed asyncronously.");
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
Stream reader = request.InputStream;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Hello World!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
class Client
{
public static void Main()
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.0.55:5432");
request.UserAgent = "linkToShare - HTTPWebRequest";
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "data data data data.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
}
The problem with your code is that in the server you are calling EndGetContext method which will set the WaitHandle and immediately close the server before it had any time to send the response.
Here's a slight modification of your code.
Server:
class Program
{
private static ManualResetEvent _waitHandle = new ManualResetEvent(false);
static void Main()
{
NonblockingListener(new string[] { "http://+:5432/" });
}
public static void NonblockingListener(string[] prefixes)
{
using (var listener = new HttpListener())
{
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
var result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
Console.WriteLine("Waiting for request to be processed asyncronously.");
// Block here until the handle is Set in the callback
_waitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}
}
public static void ListenerCallback(IAsyncResult result)
{
var listener = (HttpListener)result.AsyncState;
var context = listener.EndGetContext(result);
var response = context.Response;
string responseString = "<HTML><BODY>Hello World!</BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
// Finished sending the response, now set the wait handle
_waitHandle.Set();
}
}
Client:
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "linkToShare - HTTPWebRequest";
var valuesToPost = new NameValueCollection
{
{ "param1", "value1" },
{ "param2", "value2" },
};
var result = client.UploadValues("http://127.0.0.1:5432", valuesToPost);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
}