public void WaitForData()
{
try
{
if ( m_pfnCallBack == null )
{
m_pfnCallBack = new AsyncCallback (OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket ();
theSocPkt.thisSocket = m_clientSocket;
// Start listening to the data asynchronously
m_result = m_clientSocket.BeginReceive (theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
m_pfnCallBack,
theSocPkt);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState ;
int 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);
richTextRxMessage.Text = richTextRxMessage.Text + szData;
WaitForData();
}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void UpdateControls( bool connected )
{
buttonConnect.Enabled = !connected;
buttonDisconnect.Enabled = connected;
string connectStatus = connected? "Connected" : "Not Connected";
textBoxConnectStatus.Text = connectStatus;
}
void ButtonDisconnectClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close();
m_clientSocket = null;
UpdateControls(false);
}
}
//----------------------------------------------------
// This is a helper function used (for convenience) to
// get the IP address of the local machine
//----------------------------------------------------
String GetIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Grab the first IP addresses
String IPStr = "";
foreach(IPAddress ipaddress in iphostentry.AddressList){
IPStr = ipaddress.ToString();
return IPStr;
}
return IPStr;
}
【C#】 Socket通讯客户端程序(2)
内容版权声明:除非注明,否则皆为本站原创文章。