【问题标题】:sockets close the client when the server is closed当服务器关闭时,套接字会关闭客户端
【发布时间】:2014-01-17 07:11:52
【问题描述】:

服务器幻灯片:

    public void Hey()
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        LingerOption lo = new LingerOption(false, 0);
        sck.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Linger,lo);

        try
        {
            sck.Bind(Login.ip_ep);
            sck.Listen(100);
            Socket accepted = sck.Accept();
            byte[] buff = new byte[300000];



            MemoryStream m = new MemoryStream();


            read = accepted.Receive(buff, buff.Length, 0);
            m.Write(buff, 0, read);
            while (read > 0)
            {
                read = accepted.Receive(buff, buff.Length, 0);
                if (read != 0)
                    m.Write(buff, 0, read);


            }

            Bitmap p = new Bitmap(m, false);
            m.Dispose();
            pictureBox1.Image = p;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            accepted.Dispose();
            accepted.Close();
            sck.Dispose();
            sck.Close();


        }
        catch (Exception f)
        {
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Thread t = new Thread(Hey);
        t.Start();



    }

客户幻灯片:

 private void timer1_Tick(object sender, EventArgs e)
        {


            Bitmap b = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics g = Graphics.FromImage(b as Image);
            g.CopyFromScreen(0, 0, 0, 0, b.Size);
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox1.Image = b;
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                sck.Connect(Login.ip_ep);

                    MemoryStream s = new MemoryStream();
                    pictureBox1.Image.Save(s, System.Drawing.Imaging.ImageFormat.Png);


                    sck.Send(s.ToArray());
                    sck.Dispose();
                    sck.Close();



            }
            catch (Exception f) { 

            }



        } 

我想在关闭服务器时关闭客户端套接字,可以这样做吗? 关闭服务器并重新打开它之后的另一件事,我只允许使用每个套接字地址那是什么?

【问题讨论】:

  • 不关闭服务器套接字是否会在客户端引发异常(您正在忽略)?

标签: c# sockets tcp client


【解决方案1】:

不要忽略异常。当您在服务器关闭连接结束后写入服务器时,您将收到 IOException: 'connection reset'。如果您正在阅读,您将从 read() 获得 -1,从 readLine() 获得 null,或者对于任何其他 X,从 readXXX() 获得 EOFException。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 2013-01-16
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2015-04-07
    • 2018-06-17
    • 1970-01-01
    相关资源
    最近更新 更多