如果显示另一个表单,客户端套接字停止接收数据包 [英] Client Socket stop receive packets if another Form is showed

查看:70
本文介绍了如果显示另一个表单,客户端套接字停止接收数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



一切正常但我在这里遇到问题我会解释



我的客户端是Form1,Form2和Form3



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



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



一切都好......但是当我试图发送一个数据包来编辑这个会话时...客户端不会收到数据包直到会话是结束,表格2,3关闭并返回到form1 ...



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



客户来源



Program.cs



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

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





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





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






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



UserForm

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





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



i hope it’s clear enough and sorry for my bad English ...


i hope it's clear enough and sorry for my bad English ...

推荐答案

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



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

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



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


这篇关于如果显示另一个表单,客户端套接字停止接收数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆