如果显示另一个表单,客户端套接字停止接收数据包

时间:2014-10-23 23:09:05

标签: c# client-server

大家好我有服务器/客户端应用程序......

一切正常,但我在这里遇到了问题,我将解释

我的客户是Form1,Form2和Form3

Form1是它启动套接字并处理所有内容的主要形式......

当服务器向客户端发送[Start Session]数据包时,它将隐藏form1并显示form2,当Form2加载它时,将显示form3 ..

一切都还可以......但是当我尝试发送数据包来编辑此会话时...客户端在会话结束之前不会收到数据包,表单2,3已关闭并回到form1 ......

虽然客户端正常发送数据包,即使会话已开启..

客户来源

Program.cs的

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

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

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

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.cs

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

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;
                }
        }
    }

}

我希望它足够清楚并抱歉我的英语不好......

0 个答案:

没有答案