简体   繁体   中英

Is there a way to check socket available data, synchronously?

i want to check the socket available data to read, before i call the receive() method. but it is not working. i think the way i am checking the socket available data is not correct. this is the code:

 private Socket _clientSocket;               //Client socket

  public Form1()
    {
        InitializeComponent();

        //Check for data available before calling Receive().
        if (_clientSocket.Poll(-1, SelectMode.SelectRead))
        {
            Receive();
        }


    }

it is giving me this error: Object reference not set to an instance of an object

what is the correct way to check socket available data to read? I am thinking some kind of events but i can't figure it out..

any help?

EDIT: Button for connection:

   private void BtnConnect_Click(object sender, EventArgs e)
    {
        try
        {
            string ip = TboxIP.Text;
            int port = int.Parse(TboxPort.Text);
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Connect to the  host
            _clientSocket.Connect(IPAddress.Parse(ip), port);

            if (SocketConnected(_clientSocket) == true)
            {
                lblStatus.Text = "Socket Connection Established .. ";
            }


        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

那是您的问题,您正在Form1构造函数中访问_clientSocket,并且尚未初始化。

Look documentation: Socket.Poll() if you set the microsecond number to negative like you did, it will wait forever for any kind of response.

Use waittime based on your testing, so it is not to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM