HttpListener: как слушать запросы локальной сети? - C#
Формулировка задачи:
Почему у меня получается зайти на сервер только на ПК на котором запущенна эта программа, мне сказали, что чтобы могли подключаться из локальной сету нужно запустить в несколько потоков, но не выходит.
Так как получить доступ к серверу из локальной сети???
class Local_Host
{
public HttpListener listener1;
public string html;
public void StartHost(string ip, int port, string prefix, int count)
{
listener1 = new HttpListener();
listener1.Prefixes.Add("http://" + ip + ":" + port + "/" + prefix + "/");
listener1.Start();
for (int i = 0; i <= count; i++)
ThreadPool.QueueUserWorkItem(Potock);
}
async void Potock(object state)
{
while (true)
{
HttpListenerContext context = await listener1.GetContextAsync();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = System.IO.File.ReadAllText(html).Replace("\n", " ");
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
}Решение задачи: «HttpListener: как слушать запросы локальной сети?»
textual
Листинг программы
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
namespace ConsoleApplication209
{
class Program
{
static void Main(string[] args)
{
var server = new Local_Host(){html = "c:\\1.html"};
server.StartHost("192.168.0.104", 22234, "pref");
Console.ReadLine();
}
class Local_Host
{
public HttpListener listener1;
public string html;
public void StartHost(string ip, int port, string prefix)
{
listener1 = new HttpListener();
listener1.Prefixes.Add("http://" + ip + ":" + port + "/" + prefix + "/");
listener1.Start();
ThreadPool.QueueUserWorkItem(Potock);
}
void Potock(object state)
{
while (true)
{
HttpListenerContext context = listener1.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = File.ReadAllText(html).Replace("\n", " ");
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
}
}
}