[Mono-list] confused java programmer

Candide Kemmler candide@urbanium.tv
Wed, 17 Apr 2002 03:25:05 +0200


Hi again,

I think I must apologize for not being clear enough in my last question. 
Truth is I'm a real newbie with C# and so I tend to obfuscate code a bit 
too much.

What I'd want to do really is a very simple multi-threaded server 
application. What I mean by multi-threaded is that each connection be 
handled by a separate thread. In Java you would do something like this:

create a handler class extending Thread:

class Handler extends Thread {
	Socket socket;
	public Handler ( Socket s ) { this.socket=s; }
	public void run () {
		// handle the request...
	}
}
...

Now create a ServerSocket which would spawn a new handler Thread for 
every accepted connection:

Socket s = serversocket.accept ();
new Handler ( s ).start ();

I am experiencing massive difficulties trying to mimic this behaviour in 
C#:

I begin by creating a "Handler" class, I call "Connection":

public class Connection {
	public Socket socket;
	public Connection ( Socket s ) {
		socket = s;
	}
	public void handleConnection () {
		try {
			Console.WriteLine ( "Connection accepted" );
			socket...
		} catch ( Exception e ) {
			Console.WriteLine ( "Error....." + e );
		}
	}
}

Then, I try to make a TcpListener spawn a new Thread for every accepted 
connection, exactly like in Java:

while ( true ) {
	Socket s = myList.AcceptSocket ();
	Connection con = new Connection ( s );
	Thread handlerThread = new Thread ( new ThreadStart 
( con.handlerConnection ) );
	handlerThread.start ();
}

Well, the above code complains with a System.NullReferenceException, 
apparently due to a non-existend socket object in the threaded code.

This must all be due to my total ignorance of C# and it's handling of 
multiple threads. I've tried to fiddle a bit with delegates but without 
success.

Please somebody tell me what's wrong.

Thanks in advance,

Candide Kemmler