public static void Main(string[] args) { String roomname = "no roomname given"; Console.WriteLine("THE SIZE OF ARGS IS " + args.Length); if (args.Length < 2) { Console.WriteLine("There are less than 2 args given. This is fine for now, but in the future we need to give the room name."); } else { roomname = args [1]; int max_port = 65000; int min_port = 15000; int port_diff = max_port - min_port; int room_hash = roomname.GetHashCode(); room_hash = room_hash % port_diff; room_hash = room_hash + port_diff; room_hash = room_hash % port_diff; Console.WriteLine("Mod is " + room_hash); room_hash += min_port; Vsync.Vsync.VSYNC_GROUPPORT = room_hash; Console.WriteLine("VSYNC PORT NO IS " + room_hash); } currentRoom = new Room(roomname); ID = Path.GetRandomFileName().Replace(".", ""); Console.WriteLine("User ID IS " + ID); //Set up TCP Listener Console.WriteLine(args [0]); int port = Int32.Parse(args [0]); TcpListener server = new TcpListener(port); server.Start(); Console.WriteLine("Server has started on 127.0.0.1:{0}.\nWaiting for a connection...", port); client = server.AcceptTcpClient(); stream = client.GetStream(); Console.WriteLine("Matched with a client! Now Starting VSYNC"); VsyncSystem.Start(); Console.WriteLine("VSYNC STARTED"); String groupName = "TEST ROOM"; roomGroup = new Vsync.Group(groupName); roomGroup.ViewHandlers += (ViewHandler) delegate(View v) { VsyncSystem.WriteLine("New View: " + v); Console.Title = "View " + v.viewid + ", my rank=" + v.GetMyRank(); }; roomGroup.Handlers [UPDATE] += (Action <string, string>) delegate(string username, string val) { lock (currentRoom) { currentRoom.playerLocs [username] = val; } lock (updateLock) { updateCount++; } }; roomGroup.Handlers [LOOKUP] += (Action <string>) delegate(string s) { //VsyncSystem.WriteLine("IN LOOKUP"); lock (currentRoom) { roomGroup.Reply(currentRoom.playerLocs [s]); } }; roomGroup.Handlers [REFRESH] += (Action) delegate() { lock (currentRoom) { string reply = Extensions.FromDictionaryToJson(currentRoom.playerLocs); roomGroup.Reply(reply); } }; roomGroup.Handlers [JOIN_ROOM] += (Action <string>) delegate(string username) { lock (currentRoom) { if (currentRoom.players.Count >= MAX_IN_ROOM) { roomGroup.Reply("FULL"); } else { currentRoom.players.Add(username); roomGroup.Reply("JOINED"); } } }; roomGroup.Handlers [LEAVE_ROOM] += (Action <string>) delegate(string s) { Console.WriteLine("IN LEAVE ROOM"); lock (currentRoom) { currentRoom.playerLocs.Remove(s); currentRoom.players.Remove(s); } }; roomGroup.Join(); Console.WriteLine("Room Group Joined"); Console.WriteLine(groupName); List <String> results = new List <String> (); roomGroup.OrderedQuery(Vsync.Group.ALL, JOIN_ROOM, ID, new Vsync.EOLMarker(), results); Boolean full = false; for (int j = 0; j < results.Count; j++) { if (results [j].Equals("FULL")) { Console.WriteLine("FULL"); full = true; } } if (full) { roomGroup.OrderedSend(LEAVE_ROOM, ID); Byte[] r = Encoding.UTF8.GetBytes("ROOM FULL"); Byte[] resp = Helpers.Connections.encode(r); stream.Write(resp, 0, resp.Length); client.Close(); Console.WriteLine("LEAVING ROOM"); roomGroup.Leave(); return; } send_timer = new System.Timers.Timer(); send_timer.Elapsed += send_info; send_timer.Interval = UPDATE_RATE; send_timer.Start(); test_timer = new System.Timers.Timer(); test_timer.Elapsed += test_print; test_timer.Interval = 10000; test_timer.Start(); Byte[] bytes = new Byte[4096]; String data = null; int i = Helpers.Connections.checkRead(stream, bytes); //Continuously read from the buffer while the connection is open while (i != 0) { data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); //First request -> Respond with HTTP Change Protocol Handshake if (new Regex("^GET").IsMatch(data)) { Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String( SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes( new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups [1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) ) ) + Environment.NewLine + Environment.NewLine); stream.Write(response, 0, response.Length); //Generate and send user ID Byte[] q = Encoding.UTF8.GetBytes(ID); //Byte[] resp = Helpers.Connections.encode(q); Byte[] resp = Helpers.Connections.encode(q); stream.Write(resp, 0, resp.Length); //Start the timer and send dictionary i = Helpers.Connections.checkRead(stream, bytes); } else { //decode input and put into dictionary if valid location data Byte[] decoded = Helpers.Connections.decode(bytes); //string s = System.Text.Encoding.UTF8.GetString(decoded, 0, decoded.Length); //Console.WriteLine ("RECEIVED MESSAGE " + s); String response = Helpers.Connections.parseAndPut(decoded); //Console.WriteLine ("Received these coordinates" + response); if (response == null) { Console.WriteLine("NULL STUFF RECEIVED"); } else { still_alive = true; roomGroup.OrderedSend(UPDATE, ID, response); } i = Helpers.Connections.checkRead(stream, bytes); //Console.WriteLine ("Decoded: {0}", System.Text.Encoding.UTF8.GetString (decoded, 0, decoded.Length)); } } Console.WriteLine("Reached end of input"); Console.WriteLine("NEW"); try { roomGroup.OrderedSend(LEAVE_ROOM, ID); } catch (Exception) { Console.WriteLine("WE HAVE AN ERROR BUT WE ARE IGNORING IT NOW"); } send_timer.Stop(); //is_alive_timer.Stop (); Console.WriteLine("ROOM GROUP LEAVE"); //roomGroup.Leave(); client.Close(); }
static void Main(string[] args) { Searcher.cacheList(); int MASTER_RANK = 0; //the first one enter is master Log("Start Vsync System"); Vsync.VsyncSystem.Start(); Vsync.Msg.RegisterType(typeof(QueryMessage), 0); Vsync.Msg.RegisterType(typeof(Contact), 1); g = new Vsync.Group(GroupIdentifier); int myRank = 0; g.ViewHandlers += (Vsync.ViewHandler) delegate(Vsync.View view) { //there is changes in View Vsync.VsyncSystem.WriteLine("New view: " + view); int oldRank = myRank; int oldNbNodes = nbNodes; myRank = view.GetMyRank(); nbNodes = view.members.Length; lock (serverLocker) { //if this is Master --> start the server to receive request if (myRank == MASTER_RANK) { if (serverThread == null || !serverThread.IsAlive) { Log("I'm the Master!"); serverThread = new Thread(new ParameterizedThreadStart(startServer)); serverThread.Start(); } } else { if (serverThread != null && serverThread.IsAlive) { server.Stop(); } } } }; g.Handlers[SEARCH] += (Action <QueryMessage>) delegate(QueryMessage queryMsg) { Log(string.Format("Received search request from Master: {0}", queryMsg.query)); bool isFinalNode = (myRank == queryMsg.nbNodes - 1); int nbContacts = Int32.Parse(File.ReadLines(Searcher.dbFileName).Skip(0).Take(1).ElementAt(0)); int nbLines = nbContacts / queryMsg.nbNodes; int startIndex = nbLines * myRank; if (isFinalNode) { Console.WriteLine("Final Node"); nbLines = nbContacts - startIndex; } Searcher searcher = new Searcher(); List <Contact> localResult = searcher.search(queryMsg.query, startIndex, nbLines); g.Reply(localResult); Log(string.Format("Returned result for {0}", queryMsg.query)); }; g.Join(); Log(string.Format("Joined with Rank {0}", myRank)); Vsync.VsyncSystem.WaitForever(); Console.ReadLine(); }
public static void Main(String[] Args) { Dictionary <string, List <int> > rooms = new Dictionary <string, List <int> > (); VsyncSystem.Start(); Console.WriteLine("vsync started"); Vsync.Group lGroup = new Vsync.Group("Load Balancers"); lGroup.Handlers [UPDATE] += (Action <String, List <int> >) delegate(string id, List <int> r) { foreach (KeyValuePair <string, List <int> > entry in rooms) { try { if (Int32.Parse(id) == Int32.Parse(entry.Key)) { rooms[entry.Key] = r; return; } } catch (Exception e) { //pass through } } rooms[id] = r; Console.WriteLine("Adding {0} to dict", id); }; lGroup.Handlers [LOOKUP] += (Action <String>) delegate(string id) { //Console.WriteLine("Looking in dict for {0}:end", id); //bool contains = false; foreach (KeyValuePair <string, List <int> > entry in rooms) { //Console.WriteLine("s:{0}:f", entry.Key); try { if (Int32.Parse(id) == Int32.Parse(entry.Key)) { lGroup.Reply(entry.Value); return; } } catch (Exception e) { //pass through } } /*Console.WriteLine(rooms.ContainsKey(id)); * if (contains){ * lGroup.Reply (rooms [id]); * Console.WriteLine("Found room in dictionary!"); * } * else{ */ lGroup.Reply(new List <int>()); Console.WriteLine("Creating room in dictionary!"); }; lGroup.MakeChkpt += (Vsync.ChkptMaker) delegate(View nv){ lGroup.SendChkpt(Extensions.FromDictionaryToJson(rooms)); lGroup.EndOfChkpt(); }; lGroup.LoadChkpt += (loaddckpt) delegate(string rs) { rooms = Extensions.FromJsonToDictionary(rs); }; //loadGroup.DHTEnable (1, 1, 1, 86400000); lGroup.Join(); Console.WriteLine("Server Group Joined"); int port = Int32.Parse(Args [0]); TcpListener server = new TcpListener(port); server.Start(); Console.WriteLine("Server has started on 127.0.0.1:7000.{0}Waiting for a connection...", Environment.NewLine); int counter = 7568; String room = null; while (true) { TcpClient client = server.AcceptTcpClient(); counter++; NetworkStream stream = client.GetStream(); bool connect = true; //String room = null; while (connect) { Byte[] bytes = new Byte[4096]; String data = null; int i = Helpers.Connections.checkRead(stream, bytes); data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); //First request -> Respond with HTTP Change Protocol Handshake if (new Regex("^GET").IsMatch(data)) { Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String( SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes( new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups [1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) ) ) + Environment.NewLine + Environment.NewLine); stream.Write(response, 0, response.Length); } else { Byte[] response = Helpers.Connections.decode(bytes); string r = System.Text.Encoding.ASCII.GetString(response); //r = r.Substring(0, 10); room = r; bool isValid = true; //Console.WriteLine ("{0}", r); //Console.WriteLine ("Length: {1}, Last Char: {0}!", room.Substring ((r.Length - 1)), room.Length); if (room.Contains("j")) { Console.WriteLine("here"); try { List <List <int> > rez = new List <List <int> >(); room = room.Remove(room.IndexOf("j"), 1); Console.WriteLine(room); lGroup.OrderedQuery(1, LOOKUP, room, new Vsync.EOLMarker(), rez); List <int> ports = rez[0]; if (ports.Count == 0) { isValid = false; Console.WriteLine("BAD ID"); byte[] f = Encoding.UTF8.GetBytes("BAD ID"); f = Helpers.Connections.encode(f); stream.Write(f, 0, f.Length); } Console.WriteLine(room); //r = room; } catch (Exception e) { Console.WriteLine("Error: {0}", e); } } if (isValid) { Console.WriteLine("The room name is " + room); break; } } } List <List <int> > result = new List <List <int> > (); try { lGroup.OrderedQuery(1, LOOKUP, room, new Vsync.EOLMarker(), result); List <int> ports = result[0]; ports.Add(counter); lGroup.OrderedSend(UPDATE, room, ports); } catch (Exception e) { Console.WriteLine("DICTIONARY ADD Error: {0}", e); } /*Console.WriteLine ("good here..."); * List<int> portlst = loadGroup.DHTGet<String, List<int>>((string) room); * Console.WriteLine ("good after this ish"); * if (portlst == null) { * portlst = new List<int> (); * } * portlst.Add (counter); * Console.WriteLine ("putting"); * loadGroup.DHTPut (room, portlst); * Console.WriteLine ("put"); */ Byte[] q = Encoding.UTF8.GetBytes(counter.ToString()); Byte[] resp = Helpers.Connections.encode(q); Console.WriteLine("HEY " + "../launchServer.sh " + counter.ToString() + " " + room); Process proc = new Process { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = "../launchServer.sh " + counter.ToString() + " " + room, UseShellExecute = true, RedirectStandardOutput = false } }; proc.Start(); Console.WriteLine("A Client Connected!Handler server started."); System.Threading.Thread.Sleep(1000); stream.Write(resp, 0, resp.Length); Console.WriteLine("Port Number Sent"); } }
public static void Main(string[] args) { //Set up vsync dictionary and handlers Dictionary <string, string> valueStore = new Dictionary <string, string> (); valueStore ["user1"] = "0,1,0,1,1,2"; valueStore ["user2"] = "1,1,1,1,1,1"; const int UPDATE = 0; const int LOOKUP = 1; const int REFRESH = 2; const int REMOVE = 3; Console.WriteLine("Hello World!"); VsyncSystem.Start(); Console.WriteLine("VSYNC STARTED"); Vsync.Group g = new Vsync.Group("dataHolder"); g.ViewHandlers += (ViewHandler) delegate(View v) { VsyncSystem.WriteLine("New View: " + v); Console.Title = "View " + v.viewid + ", my rank=" + v.GetMyRank(); }; g.Handlers[UPDATE] += (Action <string, string>) delegate(string username, string val) { VsyncSystem.WriteLine("IN UPDATE"); valueStore[username] = val; }; g.Handlers[LOOKUP] += (Action <string>) delegate(string s) { VsyncSystem.WriteLine("IN LOOKUP"); g.Reply(valueStore[s]); }; g.Handlers [REFRESH] += (Action) delegate() { string reply = Extensions.FromDictionaryToJson(valueStore); g.Reply(reply); }; g.Handlers [REMOVE] += (Action <string>) delegate(string s) { VsyncSystem.WriteLine("DELETING USER " + s); valueStore.Remove(s); }; /*g.MakeChkpt += (Vsync.ChkptMaker)delegate(View nv) { * g.SendChkpt(valueStore); * g.EndOfChkpt(); * }; * g.LoadChkpt += (loadVSchkpt)delegate(Dictionary<string, position> vs) { * valueStore = vs; * }; */ g.Join(); //Quick visual check to make sure initialization goes smoothely //UNNECESSARY -> TAKE OUT LATER List <string> valuesDic = new List <string> (); g.Query(1, REFRESH, new EOLMarker(), valuesDic); Console.WriteLine(valuesDic [0]); //Set up TCP Listener TcpListener server = new TcpListener(7569); server.Start(); Console.WriteLine("Server has started on 127.0.0.1:7569.{0}Waiting for a connection...", Environment.NewLine); //Listen for connections while (true) { TcpClient client = server.AcceptTcpClient(); handler h = new handler(client, g); //Spin off new thread to handle clients as they arrive Thread handler = new Thread(new ThreadStart(h.handle)); handler.Start(); Console.WriteLine("A Client Connected!"); } }
static void Main(string[] args) { Searcher.cacheList(); int MASTER_RANK = 0; //the first one enter is master Log("Start Vsync System"); Vsync.VsyncSystem.Start(); Vsync.Msg.RegisterType(typeof(QueryMessage), 0); Vsync.Msg.RegisterType(typeof(Contact), 1); g = new Vsync.Group(GroupIdentifier); int myRank = 0; g.ViewHandlers += (Vsync.ViewHandler)delegate(Vsync.View view) { //there is changes in View Vsync.VsyncSystem.WriteLine("New view: " + view); int oldRank = myRank; int oldNbNodes = nbNodes; myRank = view.GetMyRank(); nbNodes = view.members.Length; lock (serverLocker) { //if this is Master --> start the server to receive request if (myRank == MASTER_RANK) { if (serverThread == null || !serverThread.IsAlive) { Log("I'm the Master!"); serverThread = new Thread(new ParameterizedThreadStart(startServer)); serverThread.Start(); } } else { if (serverThread != null && serverThread.IsAlive) { server.Stop(); } } } }; g.Handlers[SEARCH] += (Action<QueryMessage>)delegate(QueryMessage queryMsg) { Log(string.Format("Received search request from Master: {0}", queryMsg.query)); bool isFinalNode = (myRank == queryMsg.nbNodes - 1); int nbContacts = Int32.Parse(File.ReadLines(Searcher.dbFileName).Skip(0).Take(1).ElementAt(0)); int nbLines = nbContacts / queryMsg.nbNodes; int startIndex = nbLines * myRank; if (isFinalNode) { Console.WriteLine("Final Node"); nbLines = nbContacts - startIndex; } Searcher searcher = new Searcher(); List<Contact> localResult = searcher.search(queryMsg.query, startIndex, nbLines); g.Reply(localResult); Log(string.Format("Returned result for {0}", queryMsg.query)); }; g.Join(); Log(string.Format("Joined with Rank {0}", myRank)); Vsync.VsyncSystem.WaitForever(); Console.ReadLine(); }