Reputation: 651
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);
}
}
Upvotes: 1
Views: 2470
Reputation: 99
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
Upvotes: 2
Reputation: 5732
That's your problem, you are accessing _clientSocket in the Form1 constructor and it has not been initialised yet.
Upvotes: 2