Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace MyFirstWebServer
- {
- public class Server
- {
- private TcpListener tcpListener;
- private Thread listenThread;
- public Server()
- {
- this.tcpListener = new TcpListener(IPAddress.Any, 3000);
- this.listenThread = new Thread(new ThreadStart(ListenForClients));
- this.listenThread.Start();
- }
- public void ListenForClients()
- {
- this.tcpListener.Start();
- while (true)
- {
- //blocks until a client has connected to the server
- TcpClient client = this.tcpListener.AcceptTcpClient();
- //create a thread to handle communication
- //with connected client
- Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
- clientThread.Start(client);
- }
- }
- private void HandleClientComm(object client)
- {
- TcpClient tcpClient = (TcpClient)client;
- NetworkStream clientStream = tcpClient.GetStream();
- ASCIIEncoding encoder = new ASCIIEncoding();
- byte[] message = new byte[tcpClient.ReceiveBufferSize];
- int bytesRead;
- string messageString = string.Empty;
- while (true)
- {
- bytesRead = 0;
- try
- {
- //blocks until a client sends a message
- bytesRead = clientStream.Read(message, 0, message.Length);
- //if(bytesRead > 0)
- // break;
- }
- catch
- {
- //a socket error has occured
- break;
- }
- if (bytesRead == 0)
- {
- //the client has disconnected from the server
- break;
- }
- }
- //Console.WriteLine("Received from Client: " + encoder.GetString(message));
- byte[] buffer = encoder.GetBytes("HTTP 1.1 200 OK");
- clientStream.Write(buffer, 0, buffer.Length);
- clientStream.Flush();
- tcpClient.Close();
- }
- }
- }
Add Comment
Please, Sign In to add comment