Click here to Skip to main content
15,874,995 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Guys,

i have a TCP Server & Client see below for complete code. Can someone please provide sample code or edit my code on how i could make this Multithreaded please.

Also, i want the client to receive a message from the server, instead of sending the message to the server.
if someone could help me with that also it would be greatly appreciated.

Matt

SERVER
C#
public static void Main (string[] args)
{
try {
	while (true) {
			IPAddress ipAd = IPAddress.Parse ("127.0.0.1");
			TcpListener myList = new TcpListener (ipAd, 8001);
			myList.Start ();
			Console.WriteLine ("The server is running at port 8001...");    
			Console.WriteLine ("The local End point is  :" +
			myList.LocalEndpoint);
			Console.WriteLine ("Waiting for a connection.....");
			Socket s = myList.AcceptSocket ();
			Console.WriteLine ("Connection accepted from " + s.RemoteEndPoint);
			byte[] b = new byte[100];
			int k = s.Receive (b);
			Console.WriteLine ("Recieved...");
			string Command = string.Empty;
			for (int i = 0; i < k; i++) {
				Command = Command + Convert.ToChar (b [i]);
			}
			Console.WriteLine (Command);
			ASCIIEncoding asen = new ASCIIEncoding ();
			s.Send (asen.GetBytes ("The string was recieved by the server."));
			Console.WriteLine ("\nSent Acknowledgement");        
			s.Close ();
			myList.Stop ();
		}
	} catch (Exception e) {
		Console.WriteLine ("Error..... " + e.StackTrace);
	}    
}


CLIENT

C#
try {
				while(true)
				{
				TcpClient tcpclnt = new TcpClient();
				Console.WriteLine("Connecting.....");

				tcpclnt.Connect("127.0.0.1",8001);
				// use the ipaddress as in the server program

				Console.WriteLine("Connected");
				Console.Write("Enter the string to be transmitted : ");

				String str=Console.ReadLine();
				Stream stm = tcpclnt.GetStream();

				ASCIIEncoding asen= new ASCIIEncoding();
				byte[] ba=asen.GetBytes(str);
				Console.WriteLine("Transmitting.....");

				stm.Write(ba,0,ba.Length);

				byte[] bb=new byte[100];
				int k=stm.Read(bb,0,100);

				for (int i=0;i<k;i++)
					Console.Write(Convert.ToChar(bb[i]));

				tcpclnt.Close();
				}
			}

			catch (Exception e) {
				Console.WriteLine("Error..... " + e.StackTrace);
			}
Posted

You're not far off!

Here's a few things:

I'd replace this:
IPAddress ipAd = IPAddress.Parse ("127.0.0.1");
TcpListener myList = new TcpListener (ipAd, 8001);

with this:
TcpListener myList = new TcpListener (IPAddress.Any, 8001);

Reason being that 127.0.0.1 will only work on your computer and not incoming connections from other computers.

On the server you are accepting a socket, but on the client a TcpClient. Use the same (TcpClient) on both sides. Once the connection is established both ends work exactly the same way then. Use AcceptTcpClient instead of AcceptSocket.

When reading and writing to/from the stream, you need to put the read/write calls in a loop. Not all the data can be guaranteed in a single call as it gets lumped in packets on the wire. If you try to read 8k of data but the read call only returns 5000 bytes, you need to call it again to collect the rest.

As for the original question you need to determine if connections are going to be brief affairs (threadpool) or long-running things (new thread). Either way, put the Accept in a loop, and pass the supplied TcpClient as the parameter to the threadstart. If that doesn't make sense, let me know and I'll explain further.
 
Share this answer
 
Not exactly a direct answer to your question, but some advice I often give to people writing socket code:-

Don't.

Spend a little time learning ZeroMQ[^]. It's comprehensive, easy to use, bulletproof, multiplatform, multithreaded, and pretty much anything else you could want.

Writing socket code is deceptively easy. Single-threaded code that performs poorly is a doddle. Bulletproof multithreaded implementations are *not* easy, there are gotchas awaiting you.

Do yourself a favour and use ZeroMQ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900