1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; /* * Based on an example from Stackoverflow. */ class MainClass { public static void Main() { TcpListener client = new TcpListener(9050); client.Start(); Console.WriteLine("Waiting for clients..."); while (true) { while (!client.Pending()) Thread.Sleep(1000); ConnectionThread newconnection = new ConnectionThread(client); } } } class ConnectionThread { public TcpListener mThreadListener; /* * Constructor * */ public ConnectionThread(TcpListener lis) { mThreadListener = lis; ThreadPool.QueueUserWorkItem(new WaitCallback(HandleConnection)); } /* * Connection handler * */ public void HandleConnection(object pStateObj) { int lDataRead; byte[] lData = new byte[1024]; TcpClient lClientSock = mThreadListener.AcceptTcpClient(); NetworkStream lNetStream = lClientSock.GetStream(); string lClientSys = lClientSock.Client.RemoteEndPoint.ToString(); lData = Encoding.ASCII.GetBytes(String.Format("Hi {0}", lClientSys)); lNetStream.Write(lData, 0, lData.Length); while (true) { lData = new byte[1024]; lDataRead = lNetStream.Read(lData, 0, lData.Length); lNetStream.Write(lData, 0, lDataRead); Console.WriteLine(string.Format("{0} says : {1}\n\n", lClientSys, Encoding.ASCII.GetString(lData))); } lNetStream.Close(); lClientSock.Close(); } } |
hmmm… i’ll try to reproduce that. thanks for the hint.
when i close client… the server looping more and more… how to fixed..
thanks for feedback. but can you be a little more precise? what is not efficient, where in the code and why? you got a good example?
thanks in advance for your sharing.
simple ‘looks like the java way) but not effcient… you should read msdn dedicated articles