Socket struggling

JCDenton

Member
Joined
Feb 3, 2005
Messages
10
i found a piece of code on the web that was designed to show the basic functionality of the socket class, so I decided to comment the code as it was uncommented and see where I would be struggling...

Code:
private void btnListen_Click(object sender, System.EventArgs e)
    		{
			//starts the server
    			btnListen.Enabled = false;
    			btnConnect.Enabled = false;
    			txtServerIP.Enabled = false;
    		
    			myThread = new Thread(new ThreadStart(RunListener));
    			myThread.Start();
			//thread listening for incoming connections
    		}

		private void RunListener()
    		{
			//get ready for connections
    			myListener = new TcpListener(IPAddress.Any, 9000);
			//accept from any ip on port 9000
    			myListener.Start();
			//start tcp listener
    			lstChat.Items.Add("Listening for a client...");
			//notify user
    			while (!myListener.Pending())
			//this loops runs while the listener is waiting for incoming connections
    			{
    				Thread.Sleep(100);
				//wait a while to mitigate the load on system resources
    			}
    			lstChat.Items.Add("Connecting...");
			//notify user
    			myClient = myListener.AcceptTcpClient();
			//defined globally in the form class definition [???]
			//as an instance of the tcpClient class [protected]
    			myThread = new Thread(new ThreadStart(ReceiveData));
			//prepare for incoming data
    			myThread.Start();
			//incoming data thread
    		}

		private void ReceiveData()
    		{
		//this is the most discombobulating thread in the program
		//IMHO
    			int i;		//not sure what it is used for
    			string sStreamString;	//:S
    			byte[] baData = new byte[1024];
			//byte array with 1024 elements...
    			myStream = myClient.GetStream();
			// myStream is a netWork Stream [protected]
			//attaches a stream to the tcpClient
    			lstChat.Items.Add("Connected!");
			//notify user
    			while (true)
			//run infinite loop until the peer decides to close
			
    			{
    				i = myStream.Read(baData, 0, baData.Length);
				//Im gonna guess here... ...this reads the first Kb [array of 1024 bytes...] of the incoming data and assigns the contents to an int???? :S or does i contain the length of the read data...?
    				sStreamString = Encoding.ASCII.GetString(baData);
				//sStreamString now contains the byte array contents... converted into/read as ASCII keycodes....
    				if (sStreamString.IndexOf("/close") == 0)
				//if /close is found then break the loop as we are closing?
    				{
    					break;
    				}
    				lstChat.Items.Add("<< " + sStreamString);
				//show the contents of the string
    			}
			//we received the close command so confirm it
    			baData = Encoding.ASCII.GetBytes("/close");
			//fill our byte array with the close command
    			myStream.Write(baData, 0, baData.Length);
			//write this from pos 0...?
    			myStream.Close();
    			myClient.Close();
			//dont need tcp client and network stream no more
    			lstChat.Items.Add("Connection closed.");
			//notify user
    		}

		private void btnConnect_Click(object sender, System.EventArgs e)
		//clicked to connect
    		{
    			btnListen.Enabled = false;
    			txtServerIP.Enabled = false;
    			btnConnect.Enabled = false;
    			lstChat.Items.Add("Connecting...");
			//notify user
    			myClient = new TcpClient(txtServerIP.Text, 9000);
			//connect....what if it fails to connect? try + catch?
    			myThread = new Thread(new ThreadStart(ReceiveData));
			//go check for incoming data
    			myThread.Start();
    		}
		private void btnSend_Click(object sender, System.EventArgs e)
    		{
    			if (txtMessage.Text != "")
			//aslong as we have a msg to send
    			{
    				byte[] baData = new byte[2];
				//a two byte array..?:S
    				baData = Encoding.ASCII.GetBytes(txtMessage.Text);
				//load msg into byte array...
    				myStream.Write(baData, 0, baData.Length);
				//send the contents of the byte array..from pos 0 to the end..
    				lstChat.Items.Add(">> " + txtMessage.Text);
    				txtMessage.Clear();
    				txtMessage.Focus();		//obvious
    			}
    			else
    				txtMessage.Focus();
				//we have no msg
    		}

1) It seems to be missing code to check whether there is a connection before sending which might be a good idea incase the connection is lost... Would a try/catch block solve this?

2)The amount of data send seems to be limited to a single Kb [I wouldnt go much larger] as a byte array is used with 1024 elements..

3)Im not sure why a byte array is used of only 2 elements which contains the data to be send...

4) What happens if the data arrival loop is executing while data is still missing. Would the following be a solution? :

Data Arrives
Get the first byte denoting the amount of chars contained in the message
If the array does not contain that much data yet continue adding to the array [somehow]

5) How would one go about setting up a tcp server to accept multiple connections? simply create an array of threads [resources consuming?] or would the threads also need variable arrays as otherwise each thread element in the thread array would be accessing the same variable? (hope that made sense)


Thank you :)
 
For point 5 you could have a single listener that would spawn a new thread for each incomming request and destroy the thread when the client disconnects / timesout. This could get resource hungry but that depends on how many clients you need to support.
Looking over the code though it does seem to have some oddities - assigning a value to i (the number of bytes read) and never using it, not sure about the byte array of 2 bytes either.
Using a 1K byte array is probably so the data can be snt / received in chunks over the network.
If you search these forums (have a look in the code library) Im sure somebody has posted an example of a basic network app.
 
Async callbacks are 10 times faster than threads (at least for this specific program design)

Get a TCP/IP Book!
 
Thanx PlausiblyDamp :)

Getting a tcp/ip book would be beneficial to the current knowledge that I have of the protocol so its a good idea but, at the moment I need to know how to deal with multiple connections in c#....

Any tutorial links would also be very much appreciated! :)
 

Similar threads

P
Replies
0
Views
176
Policy standard local admin account with Active Di
P
Back
Top