Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
Hello guys i have a server / client applications ...

everything working as well but i got a problem here and i will explain

my client is a Form1 , Form2 and Form3

Form1 is the main form it's starts the socket and handling everything ...

when the server send a [Start Session] Packet to the client it's shall hide the form1 and show form2 and when Form2 load it'll show form3 ..

everything is okay ... but when i tried to send a packet to edit this session while it's on ... the client do not receive the packet till the session is ended and forms 2 , 3 is closed and went back to form1 ...

although client sending packets normally even if session is on ..

Client Source

Program.cs

C#
using System;
using System.IO;
using System.Windows.Forms;
using HotCafe_Client.Network.Sockets;

using HotCafe_Client.Network;
using HotCafe_Client.Data;
using System.Collections.Generic;

namespace HotCafe_Client
{
    using System.Net.Sockets;
    using System.Net;
    using System.Net.NetworkInformation;
    using Microsoft.Win32;
   
    class Program
    {
        static MainForm MF;
        public static Network.Sockets.AsyncSocket AuthServer;
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(MF = new MainForm());
        }

        
        public static void StartEngine()
        {
            AuthServer = new AsyncSocket();
            AuthServer.OnClientConnect += new Action<AsyncSocketWrapper>(AuthServer_AnnounceNewConnection);
            AuthServer.OnClientReceive += new Action<byte[], AsyncSocketWrapper>(AuthServer_AnnounceReceive);
            AuthServer.OnClientDisconnect += new Action<AsyncSocketWrapper>(AuthServer_AnnounceDisconnection);
            if (AuthServer.Connect("192.168.1.100", 9958))
            {
                GC.Collect();
            }
        }
        public static void WriteLine(string Text)
        {
            //MF.WriteLine(Text);
        }

        public static void WriteLine(Exception Text)
        {
            //MF.WriteLine(Text.Message);
        }

        public static void WriteLine(uint Text)
        {
            //MF.WriteLine(Text.ToString());
        }
        static void AuthServer_AnnounceNewConnection(AsyncSocketWrapper obj)
        {
            Client.State client = new Client.State(obj.Socket, MF);
            obj.Connector = client;
            if (MF.client == null)
            {
                MF.client = client;
            }
            Network.Packets.ComputerInformation ComputerInformation = new Network.Packets.ComputerInformation(true, client);
            ComputerInformation.Send(client);
        }
        static void AuthServer_AnnounceDisconnection(AsyncSocketWrapper obj)
        {
            if (obj != null)
            {
                Client.State client = (Client.State)obj.Connector;
                if (client != null)
                {
                    client.Reconnect();
                }
            }
        }
        static void AuthServer_AnnounceReceive(byte[] packet, AsyncSocketWrapper obj)
        {
            try
            {
                Client.State client = (Client.State)obj.Connector;
                Network.PacketHandler.Handle(packet, client);

            }
            catch (Exception e)
            {
                Program.WriteLine(e.ToString());
            }
        }

    }
}


MainForm.cs

C#
public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        public Client.State client;
        public Data.Calculator Calc;
        public HandForm HandForm;
        public Data.Computer.Features Features;
        System.Drawing.Size OldSize;

        private void BGW_DoWork(object sender, DoWorkEventArgs e)
        {
            Program.StartEngine();
        }
        #region Form Load / Close
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            FlashWallpaper.Movie = Application.StartupPath + @"\Flash.swf";
            FlashWallpaper.Play();
            Features = new Data.Computer.Features();
            Features.Start();
            BGW.RunWorkerAsync();
            Calc = new Data.Calculator();
        }
        #endregion
        #region System Message
        public void UpdateSystemMessage(string _Message)
        {
            new Action<Control, string, int>(SetText).BeginInvoke(System_Message, _Message, 5, null, null);
        }

        private void SetText(Control ctrl, string txt, int seconds)
        {
            this.Invoke(new MethodInvoker(
            delegate()
            {
                ctrl.Text = txt;
            }));
            System.Threading.Thread.Sleep(seconds * 1000);
            this.Invoke(new MethodInvoker(            delegate()            {                ctrl.Text = string.Empty;            }));
        }
        #endregion
        #region Session Handle
        public void LogIn(Client.State _client)
        {
            switch (client.PC_USER)
            {
                case Data.Enums.ClientUser.Admin:
                    {
                        this.Hide();
                        HandForm = new HandForm(this, client);
                        HandForm.UserForm.AdminControlIsVisible = true;
                        HandForm.UserForm.UpdateStart();
                        HandForm.ShowDialog(this);
                    }
                    break;
                case Data.Enums.ClientUser.Guest:
                    {
                        switch (client.Session.Limited)
                        {
                            case true:
                                {
                                    this.Hide();
                                    HandForm = new HandForm(this, client);
                                    HandForm.UserForm.AdminControlIsVisible = false;
                                    HandForm.UserForm.UpdateStart();
                                    HandForm.ShowDialog(this);
                                    break;
                                }
                            case false:
                                {
                                    this.Hide();
                                    HandForm = new HandForm(this, client);
                                    HandForm.UserForm.AdminControlIsVisible = false;
                                    HandForm.UserForm.UpdateStart();
                                    HandForm.ShowDialog(this);
                                    break;
                                }
                        }
                        break;
                    }
            }
        }

        public void Pause(Client.State _client)
        {
            this.LoginTimer.Stop();
            this.Show();
            FlashWallpaper.Movie = Application.StartupPath + @"\Paused.swf";
            FlashWallpaper.Play();
            this.HandForm.Close();
        }

        public void Resume(Client.State _client)
        {
            
        }

        public void LogOut(Client.State _client)
        {
            this.LoginTimer.Stop();
            this.Show();
            this.HandForm.Close();
        }
        #endregion
        #region Login Handle
        private void System_Message_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                LoginForm LF = new LoginForm();
                DialogResult dr = LF.ShowDialog(this);
                if (dr == System.Windows.Forms.DialogResult.Cancel)
                {
                    LF.Close();
                }
                else if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    if (client != null)
                    {
                        Network.Packets.AdminLoginRequest AdminLoginRequest = new Network.Packets.AdminLoginRequest(true, LF.Username, LF.Password);
                        AdminLoginRequest.Send(client);
                    }
                    else
                    {
                        UpdateSystemMessage("No response from the server !!");
                    }
                    return;
                }
                else if (dr == System.Windows.Forms.DialogResult.Retry)
                {
                    if (client != null)
                    {
                        Network.Packets.LoginRequest LoginRequest = new Network.Packets.LoginRequest(true);
                        LoginRequest.Send(client);
                    }
                    else
                    {
                        UpdateSystemMessage("No response from the server !!");
                    }
                    return;
                }
            }
        }
        #endregion
    }


LoginForm.cs

C#
    public partial class LoginForm : Form
    {
        public string Username
        {
            get
            {
                return Username_Box.Text;
            }
        }
        public string Password
        {
            get
            {
                return Password_Box.Text;
            }
        }
        public LoginForm()
        {
            InitializeComponent();
        }
    }
}



HandForm.cs

C#
public partial class HandForm : Form
    {
        public UserForm UserForm;
        public MainForm MainForm;
        public Client.State client;
        bool Opened = false;
        SlidingController slider = null;
        
        public HandForm(MainForm mainForm, Client.State client)
        {
            InitializeComponent();
            this.MainForm = mainForm;
            this.client = client;
            UserForm = new UserForm(mainForm, client);
            slider = new SlidingController(UserForm, this);
        }

        private void HandForm_Load(object sender, EventArgs e)
        {
            UserForm.Show();
            slider.Initialize();
        }

        private void HandForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (Opened)
                {
                    slider.DrawUndraw();
                    this.BackgroundImage = HotCafe_Client.Properties.Resources.Show;
                    Opened = false;
                }
                else
                {
                    slider.DrawUndraw();
                    this.BackgroundImage = HotCafe_Client.Properties.Resources.Hide;
                    Opened = true;
                }
            }
        }

        private void HandForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserForm.Close();
        }
    }


UserForm
C#
public partial class UserForm : Form
    {
        private Client.State client;
        private MainForm MF;
        public UserForm(MainForm mainForm, Client.State client)
        {
            this.MF = mainForm;
            this.client = client;
            InitializeComponent();
            this.MF.Features.End();
            this.UserFormLabel.Text = client.PC_HOST;
            Network.Packets.Update Update = new Network.Packets.Update(true);
            Update.Type = Network.Packets.Update.StartTime;
            string Time;
            if (client.PC_START_TIME.Contains("م"))
            {
                Time = client.PC_START_TIME.Replace("م", "PM");
            }
            else if (client.PC_START_TIME.Contains("ص"))
            {
                Time = client.PC_START_TIME.Replace("ص", "AM");
            }
            else
            {
                Time = client.PC_START_TIME;
            }
            Update.STRING_Value = Time;
            client.Send(Update);
            Update = new Network.Packets.Update(true);
            Update.Type = Network.Packets.Update.User;
            Update.STRING_Value = client.PC_USER.ToString();
            client.Send(Update);
        }

        public bool AdminControlIsVisible
        {
            set { this.Exit_Key.Enabled = value; this.Options_Key.Enabled = value; }
        }

        private void Cafe_Key_Click(object sender, EventArgs e)
        {
            CafeForm LF = new CafeForm();
            DialogResult dr = LF.ShowDialog(this);
            if (dr == System.Windows.Forms.DialogResult.Cancel)
            {
                LF.Close();
            }
            else if (dr == System.Windows.Forms.DialogResult.OK)
            {

            }
        }

        private void Options_Key_Click(object sender, EventArgs e)
        {
            client.Session.Pause();
        }

        private void Exit_Key_Click(object sender, EventArgs e)
        {

        }

        private void Logout_Key_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure that you want to end the session ?", "HotCafe", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) == System.Windows.Forms.DialogResult.Yes)
            {
                client.Session.End();
            }
        }

        Timer TheTimer, ProgressTimer;
        public void UpdateStart()
        {
            TheTimer = new Timer();
            TheTimer.Interval = 1000;
            TheTimer.Tick += new EventHandler(TheTimer_Tick);
            TheTimer.Start();
            if (client.Session.Limited)
            {
                ProgressTimer = new Timer();
                int Mills = (client.Session.Minutes) * 60000;
                int interval = Mills / 100;
                ProgressTimer.Interval = interval;
                ProgressTimer.Tick += new EventHandler(ProgressTimer_Tick);
                ProgressTimer.Start();
            }
        }

        public void TimeEdit(int Mins)
        {
            ProgressTimer.Stop();
            int Mills = (Mins) * 60000;
            int interval = Mills / 100;
            ProgressTimer.Interval = interval;
            TimeSpan ts = DateTime.Now - client.Session.TimeStart;
            int UsedMins = ts.Minutes;
            int UsedPrgress = Mins / UsedMins * 100;
            TimeProgress.Value = UsedPrgress;
            ProgressTimer.Start();
        }
        private void ProgressTimer_Tick(object sender, EventArgs e)
        {
            if (TimeProgress.Value < 100)
            {
                TimeProgress.Value += 1;
                TimeProgress.Refresh();
            }
            else
            {
                ProgressTimer.Enabled = false;
            }
        }
        private void TheTimer_Tick(object sender, EventArgs e)
        {
            if (client.PC_USER == Data.Enums.ClientUser.Admin)
            {
                client.PC_REMAINING_TIME = "00:00:00";
            }
            else
            {
                if (client.Session.Limited)
                {
                    client.PC_REMAINING_TIME = MF.Calc.GetRemainingTime(client);
                }
                else
                {
                    client.PC_REMAINING_TIME = "00:00:00";
                }
            }
            client.PC_USED_TIME = MF.Calc.GetUsedTime(client);
            if (client.PC_USER == Data.Enums.ClientUser.Admin)
            {
                client.PC_USAGE_COST = "00:00:00";
            }
            else
            {
                if (client.Session.Limited)
                {
                    client.PC_USAGE_COST = MF.Calc.GetLimitedTimePrice(client.Session.Minutes);
                }
                else
                {
                    client.PC_USAGE_COST = MF.Calc.GetUnlimitedTimePrice(client.Session.TimeStart);
                }
            }
            if (this != null)
            {
                StartTime.Text = client.Session.TimeStart.ToString("hh:mm:ss tt");
                RemainingTime.Text = client.PC_REMAINING_TIME;
                UsedTime.Text = client.PC_USED_TIME;
                UsageCost.Text = client.PC_USAGE_COST;
            }
        }
    }


PacketHandler.cs

C#
public static class PacketHandler
    {
        public static void Handle(byte[] packet, Client.State client)
        {
            if (packet == null)
                return;
            if (client == null)
                return;

            ushort ID = BitConverter.ToUInt16(packet, 0);
            ushort Length = BitConverter.ToUInt16(packet, 2);

            switch (ID)
            {
                case 1003:
                    {
                        Message message = new Message();
                        message.Deserialize(packet);
                        if (message.MESSAGE_CONTENT.Split(new string[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries).Length > 0)
                            message.MESSAGE_CONTENT = message.MESSAGE_CONTENT.Split(new string[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        Chat(message, client);
                        break;
                    }
                case 1005:
                    {
                        Network.Packets.StartSession StartSession = new Network.Packets.StartSession();
                        StartSession.Deserialize(packet);
                        client.Session = new Data.Session(client, StartSession);
                        client.Session.Start();
                        break;
                    }
                case 1007:
                    {
                        Network.Packets.EditSession EditSession = new Network.Packets.EditSession();
                        EditSession.Deserialize(packet);
                        client.Session.Edit(EditSession.Add, EditSession.Time);
                        break;
                    }
                default:
                    {
                        client.Send(packet);
                        break;
                    }
            }
        }

        private static void Chat(Message message, Client.State client)
        {
            switch (message.MESSAGE_TYPE)
            {
                case Data.Enums.ChatType.System:
                    {
                        string M = message.MESSAGE_CONTENT.Replace("\0", "").Split('\0')[0];
                        switch (M)
                        {
                            case "ADMIN_LOGIN_NO":
                                {
                                    client.MF.UpdateSystemMessage("Invalid Username or Password!!");
                                    break;
                                }
                            case "LOGIN_REQUEST_REJECTED":
                                {
                                    client.MF.UpdateSystemMessage("Login request has been rejected!!");
                                    break;
                                }
                        }
                        break;
                    }
                case Data.Enums.ChatType.Whisper:
                    {
                        break;
                    }
            }
        }
        
    }

i hope it's clear enough and sorry for my bad English ...
Posted
Updated 24-Oct-14 5:37am
v5
Comments
[no name] 23-Oct-14 19:06pm    
Wow, forms do handle sockets. Are you really surprised that it does not work?
Ali Al-Masry 23-Oct-14 19:11pm    
form do not handle sockets socket is handled by a class ( PacketHandler )

form1 just start the socket and it's handling the whole actions of the app
Sergey Alexandrovich Kryukov 23-Oct-14 19:20pm    
Then why do you show meaningless forms to us, never anything related to sockets?
Sorry, but, due to prolonged rain, my access to your Web site is somewhat limited, and our shamans are all on vacation right now... :-)
—SA
Ali Al-Masry 23-Oct-14 20:27pm    
i am already updated the question with codes ...
[no name] 23-Oct-14 20:01pm    
Without seeing your code or your classes for your socket programming, I can only speculate that you need to make use of asynchronous methods. You can find many posts on google regarding this and asynchronous sockets.

Server Socket: http://msdn.microsoft.com/en-us/library/fx6588te%28v=vs.110%29.aspx

Client Socket: http://msdn.microsoft.com/en-us/library/bbx2eya8%28v=vs.110%29.aspx

Let me know if you have any questions, and perhaps I can help you a little.

1 solution

Honestly i didn't review your code completely. But there is strong reason for your problem.

C#
CheckForIllegalCrossThreadCalls = false;


so you bypass threading issue with your forms and socket by changing the CheckForIllegalCrossThreadCalls to false, and you didn't handle new thread for your socket. so here is the point!!!!
your socket works in your current form thread! so when socket stuck to send or receive data your form must be freeze cause they use same thread !

search about threading and put your socket send and receive in another thread than your current form thread then use delegate to invoke and pass values between your threads. your problem wouldn't be solved if your didn't use threading.

Best Regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900