I am getting an error in this code:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
richTextBox1.Text += szData;
WaitForData(m_socWorker);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
THE UNDERLINE CODE GIVES ME THIS ERROR:
Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
And one more question, how to do that when I type the string "pw1313" it executes a Console.Beep(); event?
Loading
Sam HobbsPosted Feb 13, 2010, 9:12 PM
The SetText function in the article is a little confusing. What happens is that the InvokeRequired method determines if the function is being called from a thread different from the thred that the control is in. If the threads are different, then the function gets called again but from within the thread that the control is in.
or nakashPosted Feb 15, 2010, 5:04 PM
private void ReceiveData()
{
try
{
byte[] buffer = new byte[1024];
int iRx = m_socClient.Receive(buffer);
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
if(szData == "kuku")
{
Console.Beep();
}
string Time = "[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "]";
AppendText(Time+szData+"\n");
}
catch (SocketException se)
{
//MessageBox.Show(se.Message);
}
}
And it didn't work,maybe I did something wrong?
I can't find a good OnDataReceived,but I tried the OnDataRecieved on the server program and it didn't work either.
Sam HobbsPosted Feb 15, 2010, 3:52 PM
or nakashPosted Feb 15, 2010, 8:13 AM
I just changed SetText to AppendText,you forgot to change it ;p
One more question, how do I do actions between the client and server?
I want when the client gets the string "kuku" it will make a Console.Beep event.
Sam HobbsPosted Feb 15, 2010, 3:34 AM
Be sure to also use:
As shown in the MSDN sample. Then call AppendText(szData) instead of:
or nakashPosted Feb 14, 2010, 8:53 AM
Can you show me how to combine this with my code?