System.Net.Sockets problem : New form is hanging inside my simple chat application!

  • Thread starter Thread starter Hamed_1983
  • Start date Start date
H

Hamed_1983

Guest
Hi

I have a simple chat application which connect client(s) together via my simple server application which transfer chat data between clients according to sender/receiver.

here is my code in client side to send/receive data to/from server :

public void SendData(string message)
{
NetworkStream clientStream = this._tcpClient.GetStream();

UTF8Encoding encoder = new UTF8Encoding();
byte[] buffer = encoder.GetBytes(message);

clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}



For receive data :

public void Connect()
{
this._tcpClient.Connect(this._serverEndpoint);
this.SetupRecieveCallback();
}

public void SetupRecieveCallback()
{
try
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
this._tcpClient.Client.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this._tcpClient.Client);
}
catch (Exception ex)
{
//throw ex;
}
}

public void OnRecievedData(IAsyncResult ar)
{
// Socket was the passed in object
Socket sock = (Socket)ar.AsyncState;
if (!sock.Connected)
return;

// Check if we got any data
try
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
string strRecievedData = Encoding.UTF8.GetString(m_byBuff, 0, nBytesRec);
if (!Common.IsSystemMessage(strRecievedData) && this.ServerMessageReceived != null)
{
this.ServerMessageReceived(this, new ServerMessageEventArgs(strRecievedData));
}

// If the connection is still usable restablish the callback
this.SetupRecieveCallback();
}
else
{
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
}
catch (Exception ex)
{
//throw ex;
}
}

This code works correct between client/server applications and also another chat client application (if i don't create new form), but when a message arrived from sender chat, i want to show new chat session form to start, but i don't know when show chat form, it will be hang on! can anybody help me what's the problem and how to solve it ?

Thanks in advance



Database Helper v 2.0.0

Continue reading...
 
Back
Top