Exemple #1
0
        // Add the given connection to our list of clients
        // Send a welcome to the new client, Setup a callback to receive data
        public void NewConnection(Socket sockClient)
        {
            CSocketClient client = new CSocketClient(sockClient);

            clientsList.Add(client);

            // Get current date and time.
            DateTime now         = DateTime.Now;
            String   strDateLine = "Welcome " + now.ToString("G") + "\n\r";

            //AppendToJoinLabel(client.Sock.RemoteEndPoint + " Welcome");

            // Convert to byte array and send.
            Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
            client.Sock.Send(byteDateLine, byteDateLine.Length, 0);

            client.SetupReceiveCallback(this);
        }
Exemple #2
0
        // Get the new data and send it out to all other connections.
        // Note: If no data was received the connection has probably died.
        public void OnReceivedData(IAsyncResult ar)
        {
            CSocketClient client = (CSocketClient)ar.AsyncState;

            byte[] clientData = client.GetReceivedData(ar);



            // If no data was received then the connection is probably dead
            if (clientData.Length < 1)
            {
                CatchErrorMessageBox(client.Sock.RemoteEndPoint.ToString() + "Connection Lost");
                client.Sock.Close();
                clientsList.Remove(client);
                return;
            }

            //valid data
            var str = Encoding.Default.GetString(clientData);

            AppendToTextBox(str);


            // Send the received data to all clients (including sender for echo)
            foreach (CSocketClient clientSend in clientsList)
            {
                try
                {
                    clientSend.Sock.Send(clientData);
                }
                catch
                {
                    // If the send fails the close the connection
                    CatchErrorMessageBox(client.Sock.RemoteEndPoint.ToString() + "failed to send");
                    clientSend.Sock.Close();
                    clientsList.Remove(client);
                    return;
                }
            }
            client.SetupReceiveCallback(this);
        }