// 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; } }
// Statically accept a client public static Client Create(Socket Connection) { // Create a new reader around the provided socket NetReader Reader = new NetReader(new NetworkStream(Connection)); Reader.ReadByte(); // Read the single notification byte // Return a new client, initialising it using a received ConnectMessage return new Client(Message.ReadMessage<ConnectMessage>(Reader), Connection); }