在调用 receive() 方法之前,我想检查要读取的套接字可用数据。但它不工作。我认为我检查套接字可用数据的方式不正确。这是代码:
private Socket _clientSocket; //Client socket
public Form1()
{
InitializeComponent();
//Check for data available before calling Receive().
if (_clientSocket.Poll(-1, SelectMode.SelectRead))
{
Receive();
}
}
它给了我这个错误:Object reference not set to an instance of an object
检查套接字可用数据以读取的正确方法是什么?我正在考虑某种事件,但我无法弄清楚..
有什么帮助吗?
编辑:连接按钮:
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);
}
}