Example #1
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workerSocket;

            string name     = GetSocketName(handler);
            int    bytesRec = 0;

            try
            {
                bytesRec = handler.EndReceive(ar);
            } catch (Exception e)
            {
                WriteLog(LogStrings.ExceptionWasThrown(e));
                return;
            }

            WriteLog(LogStrings.BytesWereReceivedSuccessfuly(bytesRec, name));

            string msg = Encoding.UTF8.GetString(state.buffer, 0, bytesRec);

            WriteLog(LogStrings.MessageWasReceivedSuccessfuly(msg, name));

            if (msg.IndexOf(endMessage) != -1)
            {
                Invoke(new Method(() => clientsListBox.Items.Remove(clientsListBox.Items[clientsListBox.Items.IndexOf(name)])));

                WriteLog(LogStrings.ClosingSocket(name));

                RemoveClient(name);

                try
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                } catch (Exception e)
                {
                    WriteLog(LogStrings.ExceptionWasThrown(e));
                }

                return;
            }

            string[] paths = msg.Split(';');

            string response = MultiplyVectorAndMatrix(paths[0], paths[1]);

            if (response == null)
            {
                response = invalidInputException;
            }

            byte[] bytes = Encoding.UTF8.GetBytes(response);

            WriteLog(LogStrings.AttemptingToSendMessageToClient(response, name));

            handler.BeginSend(bytes, 0, bytes.Length, 0, new AsyncCallback(SendCallback), handler);
        }