运行时的套接字超时

时间:2014-12-27 18:06:00

标签: c# sockets

嘿伙计们,我是套接字主题的新手 我真的需要你的帮助 我正在做服务器和客户端系统(比如聊天) 但是有些不同,我正在使用Windows Form Application 在我的服务器中:我有连接到服务器的所有人的插座列表,已经从服务器获得接受。 而且我想做一个计时器,它每隔X秒就会在我的列表上运行并检查这个人是否仍然是连接我的意思是,那个人仍然在互联网上连接,但仍然可以获得包裹,如果没有将他从列表。 有人可以帮我c#怎么做??

现在在服务器上如果有人退出程序或者如果互联网注销我如何检查客户端是否已经出局 若是,那么关闭他的联系? 我读了关于TimeOut但是如何使用它?如果它是usfull?

服务器:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {

        Socket sck;
        static List<Socket> acc;
        static List<Thread> thr;
        //List<UserAt> thr;
        static int port = 9000;
        static IPAddress ip;
        static Thread NewCon;

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            acc = new List<Socket>();
            //thr = new List<UserAt>();
            thr = new List<Thread>();
            NewCon = new Thread(getNewConnection);

            //Console.WriteLine("please enter your host port ");
            string inputPort = "9000";
            try
            {
                port = Convert.ToInt32(inputPort);
            }
            catch
            {
                port = 9000;
            }

            ip = IPAddress.Parse("127.0.0.1");
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(ip, port));
            sck.Listen(0);
            NewCon.Start();

        }

        /// <summary>
        /// get new connection from client
        /// </summary>
        public void getNewConnection()
        {
            while (true)
            {
                acc.Add(sck.Accept());
                var t = new Thread(() => ReciveMessage(acc.Count-1));
                t.Start();
                thr.Add(t);

              /*  UserAt a = new UserAt();
                a.index = acc.Count - 1;
                a.thread = new Thread(() => ReciveMessage(a.index));
                a.thread.Start();
                thr.Add(a);
               * */
            }
        }


        public void ReciveMessage(int index)
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(500);
                    byte[] Buffer = new byte[255];

                    int rec = acc[index].Receive(Buffer, 0, Buffer.Length, 0);
                    Array.Resize(ref Buffer, rec);
                    //MessageBox.Show(Encoding.Default.GetString(Buffer));
                    //listBox1.Items.Add(Encoding.Default.GetString(Buffer));
                    SetText(Encoding.Default.GetString(Buffer));
                }
                catch
                {
                   // thr[index].thread.Abort();
                    /*thr.RemoveAt(index);
                    for (int i = index+1; i < thr.Count;i++ )
                    {
                        thr[i].index -= 1;
                    }*/
                        break;
                }
            }
        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.listBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.listBox1.Items.Add(text);
            }
        }

        public string getIp()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;

        }
    }
}

客户端

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace Client
    {
    public partial class Form1 : Form
    {
        static string name = "";
        static int port = 9000;
        static IPAddress ip;
        static Socket sck;

        public Form1()
        {
            InitializeComponent();


        }

        public void ReciveMessage()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] Buffer = new byte[255];
                int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
                Array.Resize(ref Buffer, rec);
                SetText(Encoding.Default.GetString(Buffer));
                //MyChat.Items.Add(Encoding.Default.GetString(Buffer));
            }
        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.MyChat.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.MyChat.Items.Add(text);
            }
        }


        private void Login_Click(object sender, EventArgs e)
        {
            name = UserName.Text;

            ip = IPAddress.Parse("127.0.0.1");

            string inputPort = "9000";
            try
            {
                port = Convert.ToInt32(inputPort);
            }
            catch
            {
                port = 9000;
            }

            try
            {
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sck.Connect(new IPEndPoint(ip, port));

                ReciveMes.Enabled = true;
                byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + " connected");
                sck.Send(conmsg, 0, conmsg.Length, 0);

                SendToServer.Enabled = true;
            }
            catch
            {
                MessageBox.Show("חיבור נכשל");
            }



        }

        private void SendToServer_Click(object sender, EventArgs e)
        {
            byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + MyMessage.Text);
            sck.Send(sdata, sdata.Length, 0);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(SendToServer.Enabled)
            {
                byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + "Is Quit");
                sck.Send(sdata, sdata.Length, 0);
            }
        }

    }
}

0 个答案:

没有答案