Simple Web Server C# - c#

I need some help with this code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace HttpEcho
{
class HttpEchoProgram
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Waiting for Client...");
TcpClient newConn = server.AcceptTcpClient();
IPEndPoint iep = (IPEndPoint)(newConn.Client.RemoteEndPoint);
IPAddress add = iep.Address;
int prt = iep.Port;
Console.WriteLine("Connected with a client: {0}: {1} ", add, prt);
NetworkStream stream = newConn.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("HTTP/1.1 200 OK");
sw.WriteLine("Content-Type: text/plain");
//sw.WriteLine("Content-Length: size");
sw.WriteLine();
String line = null;
while ((line = sr.ReadLine()).Length != 0)
{
Console.WriteLine(line);
sw.WriteLine(line);
sw.Flush();
}
newConn.Close();
server.Stop();
}
}
}
I want to modify this code so it can work as a Simple Web Server that it fetches requested page in the local file system and returns it to the browser.

You can save yourself a few thousand lines of code by starting with a HttpListener instead. http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx

Related

c# windows forms app /client server /checking client input to do something is not working in

I'm creating a client server app using c# and what it does :
1- the client sends a msg then the server sends it back to the client
2- I want to check what the client send and do some process like if the client send "chrome"
the server checks it and open chrome.exe
I don't know why its not working here on my code:
when the client sends chrome it always shows client disconnected message
also i cant convert it to windows froms app its shows lots of errors
#server code!
using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
namespace consoleTcpServer {
class Program {
class ConnectionHandler {
private Socket client;
private NetworkStream ns;
private StreamReader reader;
private StreamWriter writer;
private static int connections = 0;
//The constructor take the accepted client as argument
public ConnectionHandler(Socket client) {
this.client = client;
}
public void HandleConnection() {
try {
ns = new NetworkStream(client);
reader = new StreamReader(ns);
writer = new StreamWriter(ns);
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
writer.WriteLine("Welcome to my server");
writer.Flush();
string input;
while ((input = reader.ReadLine()).Length != 0) {
if (input.Contains("chrome")) {
System.Diagnostics.Process.Start("chrome.exe", "www.google.com");
} else if (input.Contains("fox")) {
System.Diagnostics.Process.Start("firefox.exe", "www.facebook.com");
}
Console.WriteLine(input);
writer.WriteLine(input);
writer.Flush();
}
// ns.Close();
// client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
} catch (Exception) {
connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
}
}
static void Main(string[] args) {
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(localEP);
server.Listen(10);
Console.WriteLine("Waiting for a client");
while (true) {
try {
Socket client = server.Accept();
ConnectionHandler handler = new ConnectionHandler(client);
Thread thread = new Thread(new ThreadStart(handler.HandleConnection));
thread.Start();
} catch (Exception) {
Console.WriteLine("Connection failed ..");
}
//client.Close();
//server.Shutdown();
}
}
}
}
#client code
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace consoleTcpClient {
class Program {
static void Main(string[] args) {
// Console.WriteLine("Hello World!");
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
client.Connect(remoteEP);
NetworkStream stream = new NetworkStream(client);
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
String input = reader.ReadLine();
Console.WriteLine(input);
String line = null;
while (true) {
Console.Write("Enter Message for Server <Enter to Stop >: ");
line = Console.ReadLine();
//writing for server
writer.WriteLine(line);
writer.Flush();
if (line.Length != 0) {
line = "Echo: " + reader.ReadLine();
Console.WriteLine(line);
}
}
// client.Close();
}
}
}

sending additional client info to server in C#

I have written a client program using c# socket programming which will send a file to the server. Is there any way I can send a client ID (say: 1234) to the server so that the server can recognize different clients? What modification will I have to make in the following code?
// Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace FileTransferClient
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = #"D:\demo.txt";
string p = Path.GetExtension(fileName);
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
Console.WriteLine("Connected. Sending file.");
StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());
byte[] bytes = File.ReadAllBytes(fileName);
sWriter.WriteLine(bytes.Length.ToString());
sWriter.Flush();
sWriter.WriteLine(fileName);
sWriter.Flush();
Console.WriteLine("Sending file");
tcpClient.Client.SendFile(fileName);
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();
}
}
}

sending a welcome message to client's screen in c#

Here is a simple server code written in c# . I want to give a welcome message to the client as soon as it is connected to the server. The welcome message will be displayed on the client's screen. How will I do that?
partial sample code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace server
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpClient.GetStream();
string[] arr1 = new string[] { "one", "two", "three" };
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream(), arr1);
int recv = ns.Read(data, 0, data.Length); //getting exception in this line
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
}
}
what modification is needed to send the welcome message?
May be you can try something like this...
StreamWriter writer = new StreamWriter(tcpClient.GetStream);
writer.Write("Welcome!");
In Client side, you can have below code...
byte[] bb=new byte[100];
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("XXXX",1234) // xxxx is your server ip
StreamReader sr = new StreamReader(tcpClient.GetStream();
sr.Read(bb,0,100);
// to serialize an array and send it to client you can use XmlSerializer
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream, someArrayOfStrings);
tcpClient.Close(); // Add this line otherwise client will keep waiting for server to respond further and will get stuck.
//to deserialize in client side
byte[] bb=new byte[100];
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("XXXX",1234) // xxxx is your server ip
var serializer = new XmlSerializer(typeof(string[]));
var stringArr = (string[]) serializer.Deserialize(tcpClient.GetStream);

Ident server not returning Identification on port 113

I am trying to program an ident sever to deal with the identity protocol requests from an irc server that I am programming an irc client for. The problem is I try to print to the screen the what I receive but nothing prints. I am not getting an error code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConnectIRC
{
class IdentityClass
{
private const int bufSize = 32;
public void IdentityRequest() {
TcpListener listener = null;
int port = 113;
IPEndPoint hostInfo = new IPEndPoint(IPAddress.Any, 113);
listener = new TcpListener(hostInfo);
listener.Start();
byte[] rcvBuffer = new byte[bufSize];
int rec;
for (; ; )
{
TcpClient client = null;
NetworkStream netStream = null;
client = listener.AcceptTcpClient();
if (listener.Pending())
{
Console.WriteLine("Connection was made");
}
netStream = client.GetStream();
//byte[] rcvBuffer = new byte[bufSize];
rec = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
Array.Resize(ref rcvBuffer, rec);
Console.WriteLine(Encoding.ASCII.GetString(rcvBuffer));
netStream.Close();
client.Close();
}
}
}
}
This is a very basic implementation of an ident server
Obviously it only accepts one connection and closes
Note you'll need to have a port mapped through your router for this to work
public class Ident
{
private readonly TcpListener _listener;
private readonly string _userId;
public Ident(string userId)
{
_userId = userId;
_listener = new TcpListener(IPAddress.Any, 113);
}
public void Start()
{
Console.WriteLine("Ident started");
_listener.Start();
var client = _listener.AcceptTcpClient();
_listener.Stop();
Console.WriteLine("Ident got a connection");
using (var s = client.GetStream())
{
var reader = new StreamReader(s);
var str = reader.ReadLine();
var writer = new StreamWriter(s);
Console.WriteLine("Ident got: " + str + ", sending reply");
writer.WriteLine(str + " : USERID : UNIX : " + _userId);
writer.Flush();
Console.WriteLine("Ident sent reply");
}
Console.WriteLine("Ident server exiting");
}
}

unable to connect to another computer in C#

hello guyz i have made a bare bone program in C# that simply sends a message from server to client.
Now i have successfully tested both programs running on the same machines. However when i attempt to connect 2 different computers on different networks it sends me the unable to connect message.
Here the server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console
{
class Program
{
static TcpListener listener;
static void Main(string[] args)
{
/*
string name = Dns.GetHostName();
IPAddress[] address = Dns.GetHostAddresses(name);
foreach(IPAddress addr in address)
{
Console.WriteLine(addr);
}
Console.WriteLine(address[2].ToString());*/
Console.WriteLine("server");
listener = new TcpListener(IPAddress.Any, 2055);
listener.Start();
Socket soc = listener.AcceptSocket();
Console.WriteLine("Connection successful");
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.WriteLine("A test message");
sw.WriteLine("\n");
Console.WriteLine("Test message delivered. Now ending the program");
/*
string name = Dns.GetHostName();
Console.WriteLine(name);
//IPHostEntry ip = Dns.GetHostEntry(name);
//Console.WriteLine(ip.AddressList[0].ToString());
IPAddress[] adr=Dns.GetHostAddresses(name);
foreach (IPAddress adress in adr)
{
Console.WriteLine(adress);
}
*/
Console.ReadLine();
}
}
}
and here the client code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console_client
{
class Program
{
static void Main(string[] args)
{
string host_ip_address;
Console.WriteLine("Enter server ip address");
host_ip_address=Console.ReadLine();
string display;
TcpClient client = new TcpClient(host_ip_address, 2055);
Stream s = client.GetStream();
Console.WriteLine("Connection successfully received");
StreamWriter sw = new StreamWriter(s);
StreamReader sr = new StreamReader(s);
sw.AutoFlush = true;
/*while (true)
{
display = sr.ReadLine();
if (display == "")
{
Console.WriteLine("breaking stream");
break;
}
}*/
display = sr.ReadLine();
Console.WriteLine(display);
Console.ReadLine();
}
}
}
now when i enter the 127.0.0.1 in the client program it successfully connects to the server and the message is received.
However when i enter my external ip address in the client program running on another computer i am unable to connect.
Suggestions are required in this matter.
Thank you.
You can use Wireshark in the client computer and look up any tcp packet to make sure the message sent to server.

Categories

Resources