转载(TCPClient 建立连接和断开连接函数)

public bool networkbuild()//建立端口连接
    {
        if (client == null)
        {
            try
            {
                client = new TcpClient(networkip, networkport);
                netstream = client.GetStream();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return false;
        }
        return true;
    }

    public void networkclose()//关闭端口连接
    {
        if (client != null)
        {
            try
            {
                netstream.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    public bool netsendmessage(byte[] message,int length)//发送数据
    {
        if (netconnected)
        {
            try
            {
                netstream.Write(message, 0, length);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return false;
        }
        MessageBox.Show("连接已关闭");
        return false;
    }

    public bool netreadmessage(byte[] message, int length)//读取数据
    {
        try
        {
            int i = 0;
            int cont = 0;
            if (netstream != null)
            {                    
                while (i 0)
                    {
                        i += cont;
                    }
                }

            }
            else
            {
                return false;
            }
            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return false;
    }

转载于:https://www.cnblogs.com/shuaiheng/p/10767911.html

你可能感兴趣的:(转载(TCPClient 建立连接和断开连接函数))