Torna al Thread

using System; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; public class SimpleTcpSrvr { public static void Main() { int recv; byte[] data = new byte[10240]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); while(true) { try{ Console.WriteLine("Waiting for a client..."); Socket client = newsock.Accept(); IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port); //Invia il primo pacchetto al client string startdata = "HTTP/1.0 SERVER WEB\r\n Server:SERverONE\r\n\r\n"; /*Invio dei primi dati data = Encoding.ASCII.GetBytes(startdata); client.Send(data, data.Length, SocketFlags.None);*/ //Variabile ordinaria (dipende il while) bool recdata = true; while (recdata) { //Dichiarazioni e preparazione al processo data = new byte[10240]; recv = client.Receive(data); if (recv == 0) break; Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); //Ottenere comando impartito dal client int i = 0; string result = ""; string edati = Encoding.ASCII.GetString(data, 0, recv); string[] split = edati.Split(new Char[] {' '}); foreach (string s in split) { i += 1; if (i == 2) result = s; } //Aprire il file selezionato in caso che non esista alcuna corrispondenza di comando string readfile = ""; string dires = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "/www" + result; if(System.IO.File.Exists(dires) == true) { FileStream stream = File.Open(dires, FileMode.Open); StreamReader reader = new StreamReader(stream); readfile = reader.ReadToEnd(); reader.Close(); } //Preparazione dati in invio if (Path.GetExtension(dires) == ".html") startdata = "<!-- " + Encoding.ASCII.GetString(data, 0, recv) + "\nBy SERverONE -->\n\n" + readfile; else startdata = readfile; //Conversione dei byte /*System.Text.Encoding enc = System.Text.Encoding.ASCII; data = enc.GetBytes(startdata);*/ data = Encoding.UTF8.GetBytes(startdata); client.Send(data, data.Length, SocketFlags.None); recdata = false; } Console.WriteLine("Disconnected from {0}", clientep.Address); client.Close(); //System.Threading.Thread.Sleep(data.Length); } catch (Exception e) { Console.WriteLine("\n{0} Exception caught.\n", e); //Console.WriteLine("\nThere is an error.\n", e); } } newsock.Close(); } }
Copyright © dotNetHell.it 2002-2025
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5