服务器关闭时,套接字关闭客户端

时间:2014-01-17 07:11:53

标签: c# sockets tcp client

服务器幻灯片:

    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) { 

            }



        } 

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

1 个答案:

答案 0 :(得分:0)

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