我想在我調用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);
}
}
顯示初始化_clientSocket – Gary 2013-03-14 02:51:31
@Gary,我剛剛編輯的代碼。有一個連接按鈕可以初始化_clientSocket。 – Liban 2013-03-14 02:58:48