hello, i have client server program, problem here is that the client program cannot receive message sent from server. the server is working fine, can send and receive, but the client only can send, unable to receive.
please help me, thank you very much
here is the client code:
(richTextBox1 is used to display the received message)
namespace NBCS_Client
{
public partial class NBCSuser : Form
{
delegate void AppendTextCallback(string text);
public delegate void UpdateRichEditCallback(string text);
public delegate void UpdateClientListCallback();
byte[] m_dataBuffer = new byte[10];
IAsyncResult m_result;
public AsyncCallback m_pfnCallBack;
public Socket m_clientSocket;
string pcname = "";
public NBCSuser()
{
InitializeComponent();
pcnametxt.Text = pcname = Dns.GetHostName();
ipaddtxt.Text = GetHostIP();
}
void exitbtn_Click(object sender, EventArgs e)
{
if (m_clientSocket != null)
{
m_clientSocket.Close();
m_clientSocket = null;
}
Close();
}
void connectbtn_Click(object sender, System.EventArgs e)
{
// See if we have text on the IP and Port text fields
if (ipaddtxt.Text == "" || portnotxt.Text == "")
{
MessageBox.Show("Please enter IP Address and/or Port Number to connect to the Admin\n");
return;
}
try
{
UpdateControls(false); //initiatelisten
// Create socket
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
IPAddress ip = IPAddress.Parse(ipaddtxt.Text); //get remote ip & port
int iPortNo = System.Convert.ToInt16(portnotxt.Text);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo); //endpoint
m_clientSocket.Connect(ipEnd); //connect to server
if (m_clientSocket.Connected)
{
UpdateControls(true);
//Wait for data asynchronously
WaitForData();
}
}
catch (SocketException se)
{
string str;
str = "\nConnection failed, no connection from Admin\n" + se.Message;
MessageBox.Show(str);
UpdateControls(false);
}
}
public void WaitForData()
{
try
{
if (m_pfnCallBack == null)
{
m_pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.thisSocket = m_clientSocket;
// listening to the data asynchronous
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);
// textBoxstatus.Text = textBoxstatus.Text + szData;
//textBoxstatus.Text = szData;
AppendRxText(szData);
//MessageBox.Show(Convert.ToString(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 AppendRxText(string text)
{
if (this.richTextBox1.InvokeRequired)
{
AppendTextCallback d = new AppendTextCallback(AppendRxText);
this.Invoke(d, new object[] { text });
}
else
{
richTextBox1.Text = richTextBox1.Text;
}
}
private void UpdateControls(bool connected)
{
connectbtn.Enabled = !connected;
disconnectbtn.Enabled = connected;
string connectStatus = connected ? "Welcome. Successful connected with admin" : "Not Connected with admin";
textBoxstatus.Text = connectStatus;
}
void disconnectbtn_Click(object sender, System.EventArgs e)
{
if (m_clientSocket != null)
{
m_clientSocket.Close();
m_clientSocket = null;
UpdateControls(false);
}
}
void clientsendmsgbtn_Click(object sender, System.EventArgs e) //send msg to admin
{
try
{
string msg = clientsendmsgtxtbx.Text;
// networkstream code in send msg
NetworkStream networkStream = new NetworkStream(m_clientSocket);
//using system IO
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
/* Use the following code to send bytes
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
if(m_clientSocket != null){
m_clientSocket.Send (byData);
}*/
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
string GetHostIP()
{
String myHostName = System.Net.Dns.GetHostName();
// Find host by name
System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);
//String ipstring = "";
foreach(System.Net.IPAddress myipadd in myiphost.AddressList)
{
if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return myipadd.ToString();
}
}
throw new Exception();
{
};
}
private void AppendToRichEditControl(string msg)
{
// Check to see if this method is called from a thread
// other than the one created the control
if (InvokeRequired)
{
// We cannot update the GUI on this thread.
// All GUI controls are to be updated by the main (GUI) thread.
// Hence we will use the invoke method on the control which will
// be called when the Main thread is free
// Do UI update on UI thread
object[] pList = { msg };
textBoxstatus.BeginInvoke(new UpdateRichEditCallback(OnUpdateRichEdit), pList);
} //richTextBoxReceivedMsg
else
{
// This is the main thread which created this control, hence update it
// directly
OnUpdateRichEdit(msg);
}
}
// This UpdateRichEdit will be run back on the UI thread
// (using System.EventHandler signature
// so we don't need to define a new
// delegate type here)
private void OnUpdateRichEdit(string msg)
{
richTextBox1.AppendText(msg);
}//richTextBoxReceivedMsg
}
}