Click here to Skip to main content
15,921,941 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I am writing an application to send/receive some data to and from a server. I need to make a connection before sending some data and need to keep it open so that user can send data continuously. The user can close the connection at any time by clicking on disconnect button. I created 2 buttons, one to connect and one to disconnect. Code behind Disconnect button is as below:-

C#
private void button1_Click(object sender, EventArgs e)
    {
        if (tcpclnt.Connected)
        {
            tcpclnt.Client.Disconnect(false);
            stm.Close();
        }
        else
        {
            MessageBox.Show("Not Connected");
        }
    }



code behind connect button is as below:-

C#
public ASCIIEncoding asen = new ASCIIEncoding();
public TcpClient tcpclnt = new TcpClient();
public NetworkStream stm;

private void Connect_Click(object sender, EventArgs e)
{
    if (!tcpclnt.Connected)
    {
        tcpclnt.Connect("XX.XX.XX.XX", 5500);
        MessageBox.Show("Connected to server");


        stm = tcpclnt.GetStream();

        string sysname = "000B0000" + SystemName.Text.ToString();
        byte[] sys1 = asen.GetBytes(sysname);
        sys1[0] = 0; sys1[1] = 0;
        sys1[2] = 0; sys1[3] = 0xB;
        sys1[4] = 0; sys1[5] = 0;
        sys1[6] = 0; sys1[7] = 0;
        try
        {
            stm.Write(sys1, 0, sys1.Length);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            MessageBox.Show("Error in Sending data");
        }
        if (stm.DataAvailable)
        {
            try
            {
                byte[] bb = new byte[600];
                int k = 8;
                k = stm.Read(bb, 0, bb.Length);
                string value = ASCIIEncoding.ASCII.GetString(bb, 8, k - 8);
                MessageBox.Show(value.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                MessageBox.Show("Error in Reading data");
            }
        }
     }
     else {
            MessageBox.Show("Already Connected");
    }
}



Now, when I click on connect button it connects to server and works fine. Now when I clieck on Disconnect button and again click on connect button to make the connection, it's throwing an exception on tcpclient.connect line. I don't understand why or how can I solve it, Please suggest.

Thnx,
A
Posted
Comments
Sergey Alexandrovich Kryukov 1-Jul-12 2:43am    
In what line, exactly? What is exception information? Full dump, please, with all inner exceptions, recursively, and exception Stack in debug mode. You can use "Improve question" above.
--SA

1 solution

Please see my comment to the question. You should provide comprehensive exception information. But first, check up what happens on the server side. It's possible that the server is not designed to resume operation after a client is disconnected; this is a typical mistake of the beginners. Did you create two network threads on the server, one for listening and accepting new connections, and another one for reading/writing from/to network streams or remote sockets. Also, the code of the second (communication) thread should recover from an exception caused by disconnection.

So, if the server part is wrong, there could be two problems: 1) no code is listening for a connection anymore after first connection and then disconnection; 2) the disconnection by the client side cause exception on the server side; and after this exception the communication thread not communicating anymore. Please check up it all.

[EDIT]

Thank you for clarification. There is a problem on client side.
First, pay attention, TcpClient implements System.IDisposable, but you forgot to call Dispose with the instance of the TcpClient after you disconnected. It is not like a new one. Also, try to create a new instance before each connection, tcpclnt = new TcpClient().

—SA
 
Share this answer
 
v2
Comments
Aduu 1-Jul-12 3:23am    
Actually there is a system running as a server which is further making connectinos with sub systems we call them test system. First we need to make a connection with the server by giving IP address and Port which I am doing using tcpclnt.connect. After that I need to send a string to that server with that subsytem name with which I want to connect ( This will be entered by user on run time). Clicking on connect button will make a connection with server and send this string to server. Once we send this string to server, it will make a connection with that system and then we can send messages further.

Now user may want to change this sub system after some time, so they can click on Disconnect button, that sould drop current connection and then can re-enter another system name and click connent. Which should make a connection with server and then with that sub system. But in my case its giving following error on tcpclnt.connect line. First time I click on connect button its working, but if I click it after clicking Disconnect, its giving follwoing error.

System.Net.Sockets.SocketException was unhandled
Message=A connect request was made on an already connected socket
Source=System
ErrorCode=10056
NativeErrorCode=10056
StackTrace:
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at MAxx_Test_Tools.Cxxx.Connect_Click(Object sender, EventArgs e) in C:\Users\agoya3\Documents\Visual Studio 2010\Projects\MACS Test Tools\MAXX Test Tools\CXXX.cs:line 41
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at MACS_Test_Tools.Program.Main() in c:\users\agoya3\documents\visual studio 2010\Projects\MACS Test Tools\MAXX Test Tools\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Sergey Alexandrovich Kryukov 1-Jul-12 4:11am    
OK, now it's much, much better (but please add such exception dump to the text of the original question using "Improve question", remove from the comment). Please see the update of my answer, after [EDIT].
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900