CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jul 2011
    Posts
    6

    Client auto exit when connect with server

    i've had been trying out the client server program. the client exit or crash by itself when connection establish with server. this error code 10045 being use inside the server code as the socket exception, but why the client still exit automatically?

    server code:

    catch (ObjectDisposedException)
    {
    System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
    }
    catch (SocketException se)
    {
    if (se.ErrorCode == 10054) // Error code
    {
    string msg = "User no." + socketData.m_clientNumber + " Disconnected" + "\n";
    AppendToRichEditControl(msg);

    // Remove the reference to the worker socket of the closed client
    // so that this object will get garbage collected
    m_workerSocketList[socketData.m_clientNumber - 1] = null;
    UpdateClientListControl();
    }
    else
    {
    MessageBox.Show(se.Message);
    }
    }

    what can i do so client wont auto exit? modify code in client or server or both?
    thanks in advance.

  2. #2
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Client auto exit when connect with server

    Kinda hard to guess why your client is exiting when you do not show any client code.

    btw use code tags when posting code.
    Always use [code][/code] tags when posting code.

  3. #3
    Join Date
    Jul 2011
    Posts
    6

    Re: Client auto exit when connect with server

    o, ok i post the client code below, im doing in GUI

    Code:
    namespace NBCS_Client
    {
        public partial class NBCSuser : Form
        {
            byte[] m_dataBuffer = new byte[10];
            IAsyncResult m_result;
            public AsyncCallback m_pfnCallBack;
            public Socket m_clientSocket;
    
            public NBCSuser()
            {
                InitializeComponent();
                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);
                    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);
                }
            }
            void clientsendmsgbtn_Click(object sender, EventArgs e)
            {
                try
                {
                    string msg = clientsendmsgtxtbx.Text;
                    NetworkStream networkStream = new NetworkStream(m_clientSocket);
                    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);
                }
            }
            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);
                    servermsgtxtbx.Text = servermsgtxtbx.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)
            {
                connectbtn.Enabled = !connected;
                disconnectbtn.Enabled = connected;
                string connectStatus = connected ? "Successful connected with admin" : "Not Connected with admin";
                servermsgtxtbx.Text = connectStatus;
            }
    
             void disconnectbtn_Click(object sender, EventArgs e)
            {
                if (m_clientSocket != null)
                {
                    m_clientSocket.Close();
                    m_clientSocket = null;
                    UpdateControls(false);
                }
            }
            string GetHostIP()
            {      
            String myHostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);
            foreach(System.Net.IPAddress myipadd in myiphost.AddressList)
            {
                if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
    	        {
                    return myipadd.ToString(); 
                }
            }
            throw new Exception();
                {
                };
            }
            private void clearbtn_Click(object sender, EventArgs e)
            {
                servermsgtxtbx.Clear();
            }
        }
    }
    i really had no idea why it happen like that. Any doubt please ask me again, anyway, thanks in advance

  4. #4
    Join Date
    Jul 2011
    Posts
    6

    Re: Client auto exit when connect with server

    Quote Originally Posted by DataMiser View Post
    Kinda hard to guess why your client is exiting when you do not show any client code.

    btw use code tags when posting code.
    thank for the reply.
    here is the client code
    Code:
    namespace NBCS_Client
    {
        public partial class NBCSuser : Form
        {
            byte[] m_dataBuffer = new byte[10];
            IAsyncResult m_result;
            public AsyncCallback m_pfnCallBack;
            public Socket m_clientSocket;
    
            public NBCSuser()
            {
                InitializeComponent();
                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);
                    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);
                }
            }
            void clientsendmsgbtn_Click(object sender, EventArgs e)
            {
                try
                {
                    string msg = clientsendmsgtxtbx.Text;
                    NetworkStream networkStream = new NetworkStream(m_clientSocket);
                    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);
                }
            }
            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);
                    servermsgtxtbx.Text = servermsgtxtbx.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)
            {
                connectbtn.Enabled = !connected;
                disconnectbtn.Enabled = connected;
                string connectStatus = connected ? "Successful connected with admin" : "Not Connected with admin";
                servermsgtxtbx.Text = connectStatus;
            }
    
             void disconnectbtn_Click(object sender, EventArgs e)
            {
                if (m_clientSocket != null)
                {
                    m_clientSocket.Close();
                    m_clientSocket = null;
                    UpdateControls(false);
                }
            }
            string GetHostIP()
            {      
            String myHostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);
            foreach(System.Net.IPAddress myipadd in myiphost.AddressList)
            {
                if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
    	        {
                    return myipadd.ToString(); 
                }
            }
            throw new Exception();
                {
                };
            }
            private void clearbtn_Click(object sender, EventArgs e)
            {
                servermsgtxtbx.Clear();
            }
        }
    }

  5. #5
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Client auto exit when connect with server

    I do not see anything there that should be causing the program to close unless of course the exit button is clicked.
    Always use [code][/code] tags when posting code.

  6. #6
    Join Date
    Jul 2011
    Posts
    6

    Re: Client auto exit when connect with server

    Quote Originally Posted by DataMiser View Post
    I do not see anything there that should be causing the program to close unless of course the exit button is clicked.
    but seriously the client will exit when server connect. i code it in 2 different projects, i run both in same computer, i try out the current ipv4 address, and 127.0.0.1, manually key random port, i even delete the socket exception error code == 10054, i try out many things but also cannot, client auto exit. The sample program i got from internet everything works fine, but when i use the code in my own GUI, it happen like that. Seriously don't know what happen.

    here is my full server code:
    Code:
    namespace NBCS_serverlogin
    {
        public partial class NBCSadmin : Form
        {
            public delegate void UpdateRichEditCallback(string text);
            public delegate void UpdateClientListCallback();
    
            public AsyncCallback pfnWorkerCallBack;
            private Socket m_mainSocket;
    
            private System.Collections.ArrayList m_workerSocketList = ArrayList.Synchronized(new System.Collections.ArrayList());
    
            private int m_clientCount = 0;
    
            public NBCSadmin()
            {
                InitializeComponent();
                // show local ip address
                ipaddtxt.Text = GetHostIP(); 
    
            }
            void connectclientbtn_Click(object sender, EventArgs e)
            {
                try
                {
                    if (portnotxt.Text == "") //port number
                    {
                        MessageBox.Show("Port Number is required");
                        return;
                    }
                    string portStr = portnotxt.Text;
                    int port = System.Convert.ToInt32(portStr);
                    // listening socket...
                    m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
                    m_mainSocket.Bind(ipLocal); //bing ip address
                    m_mainSocket.Listen(4); //start listening
                    m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); //callback from user(s)
    
                    UpdateControls(true);
    
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }
            }
           
            private void UpdateControls(bool listening)
            {
                connectclientbtn.Enabled = !listening;
                stopconnbtn.Enabled = listening;
            }
            
            public void OnClientConnect(IAsyncResult asyn) //call back that call on when client connected
            {
                try
                {
                    Socket workerSocket = m_mainSocket.EndAccept(asyn);
                    Interlocked.Increment(ref m_clientCount); // count the client, increment
                    m_workerSocketList.Add(workerSocket); // add workersocket to arraylist
                    string msg = "Welcome user " + m_clientCount + "\n"; //send welcome msg to client
                    SendMsgToClient(msg, m_clientCount);
                    UpdateClientListControl(); //update client list box
    
                    WaitForData(workerSocket, m_clientCount); //process the current connected client
    
                    m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); //socket free, then can accept connection from other clients
                }
                catch (ObjectDisposedException)
                {
                    System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }
    
            }
            public class SocketPacket
            {
                public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)
                {
                    m_currentSocket = socket;
                    m_clientNumber = clientNumber;
                }
                public System.Net.Sockets.Socket m_currentSocket;
                public int m_clientNumber;
                // Buffer to store the data sent by the client
                public byte[] dataBuffer = new byte[1024];
            }
           
            public void WaitForData(System.Net.Sockets.Socket soc, int clientNumber)
            {
                try
                {
                    if (pfnWorkerCallBack == null)
                    {
                        // Specify the call back function which is to be invoked when there is any write activity by the connected client
                        pfnWorkerCallBack = new AsyncCallback(OnDataReceived); 
                    }
                    SocketPacket theSocPkt = new SocketPacket(soc, clientNumber);
    
                    soc.BeginReceive(theSocPkt.dataBuffer, 0,
                        theSocPkt.dataBuffer.Length,
                        SocketFlags.None,
                        pfnWorkerCallBack,
                        theSocPkt);
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }
            }
            // This the call back function which will be invoked when the socket
            // detects any client writing of data on the stream
            public void OnDataReceived(IAsyncResult asyn) //detect data send from client
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;
                try
                {
                    // Complete the BeginReceive() asynchronous call by EndReceive() method
                    // which will return the number of characters written to the stream 
                    // by the client
                    int iRx = socketData.m_currentSocket.EndReceive(asyn);
                    char[] chars = new char[iRx + 1];
                   
                    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                    int charLen = d.GetChars(socketData.dataBuffer,
                        0, iRx, chars, 0);
    
                    System.String szData = new System.String(chars);
                    string msg = "" + socketData.m_clientNumber + ":";
                   
                    AppendToRichEditControl(msg + szData);
         
                    string replyMsg = "Admin Reply:" + szData.ToUpper(); //reply msg to client // + Dns.GetHostName() + ""
                    // Convert the reply to byte array
                    byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);
    
                    Socket workerSocket = (Socket)socketData.m_currentSocket;
                    workerSocket.Send(byData);
    
                    // Continue the waiting for data on the Socket
                    WaitForData(socketData.m_currentSocket, socketData.m_clientNumber);
    
                }
                catch (ObjectDisposedException)
                {
                    System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
                }
                catch (SocketException se)
                {
                    if (se.ErrorCode == 10054) // Error code 
                    {
                        string msg = "User no." + socketData.m_clientNumber + " Disconnected" + "\n";
                        AppendToRichEditControl(msg);
    
                        // Remove the reference to the worker socket of the closed client
                        // so that this object will get garbage collected
                        m_workerSocketList[socketData.m_clientNumber - 1] = null;
                        UpdateClientListControl();
                    }
                    else
                    {
                        MessageBox.Show(se.Message);
                    }
                }
            }
            // This method could be called by either the main thread or any of the
            // worker threads
            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 };
                    statuslogtxtbx.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)
            {
                statuslogtxtbx.AppendText(msg);
            }
    
            private void UpdateClientListControl()
            {
                if (InvokeRequired) // Is this called from a thread other than the one created
                // the control
                {
                    // 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
                    clientlist.BeginInvoke(new UpdateClientListCallback(UpdateClientList), null);
                }
                else
                {
                    // This is the main thread which created this control, hence update it
                    // directly 
                    UpdateClientList();
                }
            }
            void ButtonSendMsgClick(object sender, System.EventArgs e)
    		{
    			try
    			{
    				string msg = richtxtbxsendmsg.Text;
    				msg = "Admin Message: " + msg + "\n";
    				byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
    				Socket workerSocket = null;
    				for(int i = 0; i < m_workerSocketList.Count; i++)
    				{
    					workerSocket = (Socket)m_workerSocketList[i];
    					if(workerSocket!= null)
    					{
    						if(workerSocket.Connected)
    						{
    							workerSocket.Send (byData);
    						}
    					}
    				}
    			}
    			catch(SocketException se)
    			{
    				MessageBox.Show (se.Message );
    			}
    		}
    	    void stopconnbtn_Click(object sender, EventArgs e)
            {
                CloseSockets();			
    			UpdateControls(false);
            }
            string GetHostIP()
            {
                String myHostName = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);
                foreach (System.Net.IPAddress myipadd in myiphost.AddressList)
                {
                    if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return myipadd.ToString();
                    }
                }
                throw new Exception()
                {
                };
            }
             void logoutbtn_Click(object sender, EventArgs e)
            {
                CloseSockets();
                NBCSadmin adminpage = new NBCSadmin();
                adminpage.Close();
                serverlogin login = new serverlogin();
                login.Show();
            }
    		void CloseSockets()
    		{
    			if(m_mainSocket != null)
    			{
    				m_mainSocket.Close();
    			}
    			Socket workerSocket = null;
    			for(int i = 0; i < m_workerSocketList.Count; i++)
    			{
    				workerSocket = (Socket)m_workerSocketList[i];
    				if(workerSocket != null)
    				{
    					workerSocket.Close();
    					workerSocket = null;
    				}
    			}	
    		}
    		void UpdateClientList()
    		{
                clientlist.Items.Clear();
    			for(int i = 0; i < m_workerSocketList.Count; i++)
    			{
    				string clientKey = Convert.ToString(i+1);
    				Socket workerSocket = (Socket)m_workerSocketList[i];
    				if(workerSocket != null)
    				{
    					if(workerSocket.Connected)
    					{
                            clientlist.Items.Add(clientKey);
    					}
    				}
    			}
    		}
    		void SendMsgToClient(string msg, int clientNumber)
    		{
    			byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
    			Socket workerSocket = (Socket)m_workerSocketList[clientNumber - 1];
    			workerSocket.Send(byData);
    		}
            private void clearbtn_Click_1(object sender, EventArgs e)
            {
                statuslogtxtbx.Clear();
            }
    	}
    }
    thanks for reply.

  7. #7
    Join Date
    Jul 2011
    Posts
    6

    Re: Client auto exit when connect with server

    Update:

    I try to debug, i think this is the code that cause the Client program exit by itself.

    public void WaitForData()under client code

    Code:
    m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, m_pfnCallBack, theSocPkt);
    but i dont know how to fixed it, because that code also exist in the server program. not sure which side is causing the error or even any other code that causing the error.
    Please help, thanks a lot.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured