C# Web Server Connection Problem

I'm trying to make a simple C# web server that, at this stage, you can access via your browser and will just do a "Hello World".

The problem I'm having is that the server can receive data fine - I get the browser's header information - but the browser doesn't receive anything I send. Furthermore, I can only connect to the server by going to localhost (or I can't get to it by going to my IP and it's not a network setting because Apache works fine if I run that instead. Also, I'm using a port monitoring program and after I attempt a connection from a browser, the process's port gets stuck in a TIME_WAIT state even though I told the connection to close and it should be back to LISTEN.

Here's the relevant code. A couple calls might not make sense but this is a piece of a larger program.

class ConnectionHandler { private Server server; private TcpListener tcp; private ArrayList connections; private bool listening; private Thread listeningThread; public Server getServer() { return server; } private void log(String s, bool e) { server.log("Connection Manager: " + s, e); } private void threadedListen() { while (listening) { try { TcpClient t = tcp.AcceptTcpClient(); Connection conn = new Connection(this, t); } catch (NullReferenceException) { log("unable to accept connections!", true); } } log("Stopped listening", false); } public void listen() { log("Listening for new connections", false); tcp.Start(); listening = true; if (listeningThread != null && listeningThread.IsAlive) { listeningThread.Abort(); } listeningThread = new Thread(new ThreadStart( this.threadedListen)); listeningThread.Start(); } public void stop() { listening = false; if (listeningThread != null) { listeningThread.Abort(); log("Forced stop", false); } log("Stopped listening", false); } public ConnectionHandler(Server server) { this.server = server; tcp = new TcpListener(new IPEndPoint( IPAddress.Parse(""), 80)); connections = new ArrayList(); } } class Connection { private Socket socket; private TcpClient tcp; private ConnectionHandler ch; public Connection(ConnectionHandler ch, TcpClient t) { try { this.ch = ch; this.tcp = t; ch.getServer().log("new tcp connection to " + this.tcp.Client.RemoteEndPoint.ToString(), false); NetworkStream ns = t.GetStream(); String responseString; Byte[] response; Int32 bytes; responseString = String.Empty; response = new Byte[512]; bytes = ns.Read(response, 0, response.Length); responseString = System.Text.Encoding.ASCII.GetString(response, 0, bytes); ch.getServer().log("Received: " + responseString); String msg = "<html>Hello World</html>"; String fullMsg = "HTTP/1.x 200 OK\r\n" + "Server: Test Server\r\n" + "Content-Type: text/html; " + "charset=UTF-8\r\n" + "Content-Length: " + msg.Length + "\r\n" + "Date: Sun, 10 Aug 2008 22:59:59 GMT" + "\r\n"; nsSend(fullMsg, ns); nsSend(msg, ns); ns.Close(); tcp.Close(); } catch (ArgumentNullException e) { ch.getServer().log("connection error: argument null exception: " + e); } catch (SocketException e) { ch.getServer().log("connection error: socket exception: " + e); } } private void nsSend(String s, NetworkStream ns) { Byte[] data = System.Text.Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); ns.Flush(); ch.getServer().log("Sent: " + s); } }

Does anyone have any ideas? It feels like it's gotta be something stupid on my part but I just don't know what. I'd really appreciate any insight


You might like to know that you can use HttpListener to write a basic web-server very easily - this deals with most of the painful bits, letting you concentrate on writing the actual code. The MSDN page gives an example.

Note that this uses HTTP.SYS, which is good - but means that non-admins need to be explicitly given access to open ports; on xp you can do this with httpcfg; on vista you can use netsh. See here for more.

One thing which isn't a problem at the moment but might be later on is that your content length is based on the Unicode length of the message string, not the binary length.

There's also rather a lot going on in the Connection constructor - stuff that really doesn't belong in a constructor at all, IMO. It also doesn't close things if exceptions occur.

Have you looked at what's going on in a network tracer like WireShark? That would be the easiest way of seeing whether any data is getting sent back to the client.

Alternatively, post a short but complete version of your code which we can compile and run ourselves.

Maybe I'm just missing something but the reason you can only connect on localhost is because the IP you are listening on is, this makes the TCPListener only listen on that IP address. And I don't see anywhere you are calling any client disconnect, the TCPListener is a blocking call, so it sits there forever until a connection is made. In my past experience with TCP/IP and the TCPListener, TCPClient classes there is not much of a way to force the listener to drop it's connection until you drop the client connection. Calling TCPListener.Abort() doesn't drop the client connection which keeps the port blocked up.

Category:c# Time:2008-10-26 Views:0
Tags: c# connection

Related post

  • I keep getting server connection problems when I try to connect to a radio broadcast. It tells me to change my proxy settings and I have no idea how to go about that. 2013-07-24

    Original title: Media Player I keep getting server connection problems when I try to connect to a radio broadcast. It tells me to change my proxy settings and I have no idea how to go about that. I switched to Real Player as my alternate choice on th

  • 413 request entity too large + The web server connection was closed | Error 64 2011-02-15

    I'm currently hosting a django project on Apache + nginx. When I try to upload a large file I get a 413 request entity too large error message. I also have a django-cms project and when I tried to upload a file which is anything over 5meg I get an er

  • cannot display sent items - server connection problem 2014-01-09

    cannot display send email information. server connection problem --------------Solutions------------- which mail client you are using ? , Office outlook or Outlook Express ? Outlook Can you help me please? Can you help me please? Hi Rosemary, Could y

  • java client web-server connect to multi web-server 2011-11-11

    I have to do an implementation for a class in the Java language by using Tomcat 7 and Axis2 under Ubuntu 11.10 32bit. The requirement is to make a dynamic web-server project for simple registration, register and unregister course. Also, each faculty

  • Paste (Python) Web Server - Autoreload Problem 2009-08-10

    When I start the `Paste' web server in daemon mode, it seems to kill off it's ability to reload when the timestamp of a source file is updated. Here is how I start the daemon... cd ${project} && ../bin/paster serve --reload --daemon developme

  • Android - web server connectivity and authentification 2011-04-28

    I need my app to be able communicate with a web server. The problem is I want web server to respond only to requests made from real android phones. So, is there any way to make sure, that server works only with real phones? It should reject anything

  • SQL Server Connection Problems 2009-08-13

    I have one server out of three which cannot connect to our sql server 2000 using the FQDN but can connect using the non FQDN. None of the the other servers are having this problem. This problem occurs under ADO connections to a SQL Server 2000 databa

  • apache web server configuration problem 2010-05-19

    i want to have apache server to serve only /var/www/ directory now it serves all my files on system from directory "/" i tried to edit httpd.conf placed in /etc/apache2 and placed the folllowing content in it(intially it was empty) <Directory /

  • tomcat sqlite jdbc on server connection problem 2010-12-20

    Hi i want to upload my wicket project into the tomcat server. But in project i 've connected to db file like this : connection=DriverManager.getConnection("jdbc:sqlite:C:\Users\myPC\gr27hbs.db"); I'll make war file but server doesn't have db file.So

  • Remote web workplace connection problem Win 8 2012-07-15

    I have upgraded to Win 8 on my PC at home. Now I can't connet to the win 7 PC at work. I get to the screen where I choose the PC to connect to and then nothing happens. I can connect without a problem from my Win 7 Laptop. Please help. Thanx. David.

  • Consistent server connection problem installing Microsoft AutoUpdate 2.3.3. for my Mac OS X, v. 10.5.8. 2013-04-30

    I need to install the critical Microsoft AutoUpdate 2.3.3. for my Mac OS X, version 10.5.8. But each time I have tried over the last several months I am told that "The connection to the update server was interrupted", and to wait a few minutes and tr

  • J2me web service connection problem 2009-11-19

    i'm trying to connect to a php web service using kxml-rpc api and the code is as simple as this: XmlRpcClient xmlrpc = new XmlRpcClient("http://***ip here***:88/secure/service"); Vector parameters = new Vector(); parameters.addElement("value"); Strin

  • Django-pyodbc SQL Server/freetds server connection problems on linux 2010-05-07

    Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnectW)') I'm migrating from developing on a windows development machine to Linux machine in production and I'm having iss

  • Intermittent SQL Server Connection problems 2010-06-20

    I'm performing a small load test on my Centos PHP server, which is connecting to SQL server on Windows 2003. It's doing about 60 tps. Around 1-10 out of every 1000 connections fail when I start up the load with a "cannot connect to the database." How

  • SQL Server connection problem 2010-11-04

    I added an external Data Source to my C# app (I've placed it on the root directory in a folder named 'data') but when I run the program I get an error at con.Open(): An attempt to attach an auto-named database for file C:\Users\alex\documents\visual

  • Amazon web services connection problem 2011-08-09

    I created the instance of linux on EC2. I followed the exact instructions given by Amazon web services. Created the private key to connect the instance.But my key gets always rejected. I post the question on amazon forum,but didnt get nay response. C

  • blackberry server connection problem 2011-09-19

    I want to send data to the server by using URLEncodedPost Class. I am getting error while i am trying to call the POST method. so if anybody have any idea about this method then give me some hint about it. enter code here --------------Solutions-----

  • android app/server connection problems 2012-02-09

    basically, I want my android app to talk to a server; however, the server will change ip address - how do I get the app to pick up on this and adjust the ip address its sending to accordingly? better wording: I am running a server on a local network,

  • SMTP server connection problem. 2014-01-01

    I'm running Windows 7 Home Premium w/ServPak 1. No e-mail problems until yesterday; now can't send. Get "Windows Live Mail Error ID ox800CCCOE", also Socket Error: 10060. Contacted ISP Suddenlink.net. All account settings checked good; reset password

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 2.927 (s). 13 q(s)