How to use/increment tcpListener in SingleTon Class
-
Monday, August 20, 2012 9:08 AM
Hello,
I'm writinga C#WinFormI needto connect computers(Server,Client),no matternowthe final destination.
Nowwhat I'mtrying to do is, pressing thebotónenform(StartConection) start theServerListenermakeslisteningto a newCLIENT.
The whole process oflisteningI have no problem,what Ido isincrement aServerListenerinSingletonclasstoachieve asingle connection.
This is the firsttime youusethis class.I lookedon the internetand realized thatthisclass is definedas followspublic class ServerListener { private static ServerListener serverListener; //Constarctor, only class "ServerListener" can call and use private ServerListener() { } public static ServerListener GetNewClientInstance() { if (serverListener == null) { serverListener = new ServerListener(); } return serverListener; }AndIdo not knownow whereI putall the functionalityof listening into SingleTon Class
TcpListener listenerServer = new TcpListener(IPAddress.Parse("myIp"), 11123); Thread newConnThread = new Thread(new ThreadStart(NewConnection));
thank you very much for the help//
All Replies
-
Monday, August 20, 2012 10:03 PM
There is no need to create seperate threads. Instead use a different class for each listener like the code below.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace ConsoleApplication1 { class Program { static List<ServerListener> Listeners = new List<ServerListener>(); static void Main(string[] args) { string destination; int port; ServerListener newServerListener; destination = "myIp1"; port = 11123; newServerListener = new ServerListener(destination, port); Listeners.Add(newServerListener); destination = "myIp2"; port = 11124; newServerListener = new ServerListener(destination, port); Listeners.Add(newServerListener); destination = "myIp3"; port = 11125; newServerListener = new ServerListener(destination, port); Listeners.Add(newServerListener); } } public class ServerListener { private static TcpListener listenerServer; //Constarctor, only class "ServerListener" can call and use public ServerListener(string destination, int port) { listenerServer = new TcpListener(IPAddress.Parse(destination), port); } } }jdweng

