// Private constructor - Clients can only be created by calling // the Create static method provided way below private Client(ConnectMessage m, Socket Connection) { Username = m.Username; ComputerName = m.ComputerName; this.Connection = Connection; Stream = new NetworkStream(Connection); In = new NetReader(Stream); Out = new NetWriter(Stream); MessageReceived = delegate { }; Disconnect = delegate { }; }
// Attempts to connect to a specified server with a given connection message public bool Connect(IPEndPoint Server, ConnectMessage ConnectionMessage) { // Initialise socket for TCP/IP communications Inner = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { // Try to connect Inner.Connect(Server); // Set up IO streams around the socket Stream = new NetworkStream(Inner); In = new NetReader(Stream); Out = new NetWriter(Stream); // Send off the initial connection message Send(ConnectionMessage); // Begin reading from the Server StartRead(); return true; } catch { return false; } }
// Alternative overloaded signature for next function public bool Connect(string ServerAddress, ushort Port, ConnectMessage ConnectionMessage) { IPAddress Target; if (!IPAddress.TryParse(ServerAddress, out Target)) return false; return Connect(new IPEndPoint(Target, Port), ConnectionMessage); }
// Initialise the database model from the server public static Tuple<User, Room> Initialise(Connection Server, ConnectMessage Msg) { try { // Thread safe Monitor.Enter(Lock); // Reset the signal that's set when the data's received if (InitialisedEvent == null) InitialisedEvent = new ManualResetEvent(false); InitialisedEvent.Reset(); // Reset the signal that's set when the user information's received if (UserEvent == null) UserEvent = new ManualResetEvent(false); UserEvent.Reset(); // Set the current server DataRepository.Server = Server; // Hook up network events Server.MessageReceived += MessageReceived; Server.Disconnect += Disconnected; // Hook up data changed events _Bookings.CollectionChanged += Data_CollectionChanged; _Departments.CollectionChanged += Data_CollectionChanged; _Rooms.CollectionChanged += Data_CollectionChanged; _Users.CollectionChanged += Data_CollectionChanged; _Subjects.CollectionChanged += Data_CollectionChanged; _Periods.CollectionChanged += Data_CollectionChanged; _Classes.CollectionChanged += Data_CollectionChanged; // Send the connection message Server.Send(Msg); } catch { return null; } finally { // Release the lock Monitor.Exit(Lock); } try { // Wait for both signals to fire, signalling completion InitialisedEvent.WaitOne(); UserEvent.WaitOne(); } catch { // Disconnected during initialise return null; } // Return the User and their Room (grouped together for easy return value) return new Tuple<User, Room>(CurrentUser, CurrentRoom); }