Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public sealed class ConnectionManager
- {
- TcpListener serverSocket;
- public Hashtable clientsList;
- int idCounter;
- private static volatile ConnectionManager instance;
- private static object syncRoot = new Object();
- public static ConnectionManager Instance
- {
- get
- {
- if (instance == null)
- {
- lock (syncRoot)
- {
- if (instance == null)
- instance = new ConnectionManager();
- }
- }
- return instance;
- }
- }
- private ConnectionManager()
- {
- Int32 port = 8888;
- clientsList = new Hashtable();
- IPAddress localAddr = IPAddress.Parse("127.0.0.1");
- serverSocket = new TcpListener(localAddr, port);
- serverSocket.Start();
- Console.WriteLine("Server started listening...");
- idCounter = 0;
- while(true)
- {
- TcpClient clientSocket = serverSocket.AcceptTcpClient();
- Console.WriteLine("New connection accepted with id " + idCounter);
- HandleClient hc = new HandleClient(idCounter);
- clientsList.Add(idCounter++, clientSocket);
- hc.handle();
- }
- }
- public void SendMessage<T>(Message<T> m, int connectionId)
- {
- NetworkStream clientStream = ((TcpClient)clientsList[connectionId]).GetStream();
- StreamWriter sw = new StreamWriter(clientStream);
- var js = new JsonSerializer();
- js.Serialize(sw, m);
- sw.Flush();
- clientStream.Flush();
- }
- public void foo()
- {
- Console.WriteLine("korte");
- }
- }
- class HandleClient
- {
- int connectionId;
- public HandleClient(int cId)
- {
- this.connectionId = cId;
- }
- public void handle()
- {
- Thread cThread = new Thread(start);
- cThread.Start();
- }
- private void start()
- {
- Console.WriteLine("Thread started for client " + connectionId);
- User user = new User()
- {
- connectionId = connectionId
- };
- Game.Instance.AddUser(user);
- /*clientSocket.Close();
- clientsList.Remove(connectionId);
- Console.WriteLine("Thread stopped for client " + connectionId);
- Thread.CurrentThread.Abort();*/
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement