//Parses data recieved from client and updates dictionary public void parseAndPut(Byte[] coord) { string c = System.Text.Encoding.UTF8.GetString(coord); Console.WriteLine(c); c = c.Replace("{", String.Empty).Replace("\"", String.Empty).Replace("}", String.Empty); Console.WriteLine(c); String[] parts = c.Split(':'); try { String key = parts [0].Trim(); String value = parts [1].Trim(); Console.WriteLine(key); Console.WriteLine(value); g.OrderedSend(0, key, value); } catch (Exception e) { //Fail Silently } }
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(); }
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"); } }