byte[] m_dataBuffer = new byte [10];
IAsyncResult m_result;
public AsyncCallback m_pfnCallBack ;
private System.Windows.Forms.Button btnClear;
public Socket m_clientSocket;
//关闭连接
void ButtonCloseClick(object sender, System.EventArgs e)
{
if ( m_clientSocket != null )
{
m_clientSocket.Close ();
m_clientSocket = null;
}
Close();
}
//连接服务器
void ButtonConnectClick(object sender, System.EventArgs e)
{
// See if we have text on the IP and Port text fields
if(textBoxIP.Text == "" || textBoxPort.Text == ""){
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
return;
}
try
{
UpdateControls(false);
// Create the socket instance
m_clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
// Cet the remote IP address
IPAddress ip = IPAddress.Parse (textBoxIP.Text);
int iPortNo = System.Convert.ToInt16 ( textBoxPort.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint (ip,iPortNo);
// Connect to the remote host
m_clientSocket.Connect ( ipEnd );
if(m_clientSocket.Connected) {
UpdateControls(true);
//Wait for data asynchronously
WaitForData();
}
}
catch(SocketException se)
{
string str;
str = "\nConnection failed, is the server running?\n" + se.Message;
MessageBox.Show (str);
UpdateControls(false);
}
}
//发送消息
void ButtonSendMessageClick(object sender, System.EventArgs e)
{
try
{
string msg = richTextTxMessage.Text;
// New code to send strings
NetworkStream networkStream = new NetworkStream(m_clientSocket);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
//等待接收数据