Exemplo n.º 1
0
        public bool ConnectToServer(string userName)
        {
            this.userName = userName;
            bool successful = false;

            string    hostName = Dns.GetHostName(); // Retrive the Name of HOST
            IPAddress myIP     = IPAddress.Parse(Dns.GetHostByName(hostName).AddressList[0].ToString());

            int        serverPort  = 4000;
            IPEndPoint serverEndPt = new IPEndPoint(myIP, serverPort);

            successful = clientSocket.ConnectToServer(serverEndPt);
            clientSocket.ReceivedData += ClientSocket_ReceivedData;

            successful = successful && clientSocket.SendData(
                packetFactory.CreateUserPacket(userName, ((TCPClientSocket)clientSocket).IPEndPoint).ToByte());

            return(successful);
        }
Exemplo n.º 2
0
        private static void AcceptMessageWorker_DoWork(TcpClient client)
        {
            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data  = null;

            // Get a stream object for reading and writing
            NetworkStream stream = client.GetStream();

            int i;

            // Loop to receive all the data sent by the client.
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                IPacket packet = packetFactory.HandlePacket(bytes.SubArray(0, i));

                if (packet.Type == PacketType.User)
                {
                    new Task(() => NotifyUserAdded(packet)).Start();

                    // we know that only one user will be registered per client
                    users.Add(((IUsersPacket)packet).Users[0], client);
                    Console.WriteLine("\nReceived: Registration for {0}", users.Last().Key.Name);
                    Console.Write("Waiting for a connection... ");
                    var    allRegisteredUsers = packetFactory.CreateUserPacket(users.Keys.ToList());
                    byte[] msg = allRegisteredUsers.ToByte();

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent: All registered user list.");
                }
            }

            // Shutdown and end connection
            client.Close();
        }