Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Using connection continuously

Using connection continuously

Scheduled Pinned Locked Moved C#
helpsysadminquestion
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    teknolog123
    wrote on last edited by
    #1

    hi, I'm using below code for a basic client/server communication. I send a string to server and server sends it back to client with no problem. But I can do this only once and then connection goes, what should I do to be able to send more strings one after other without loosing the connection? Thanks in advance /// Server Code:

    private void button1_Click(object sender, EventArgs e)
    {
    TcpListener tcpListen = new TcpListener(IPAddress.Parse("192.168.1.6"), 1234);
    tcpListen.Start();
    Socket socket = tcpListen.AcceptSocket();

            if (socket.Connected)
            {
                while (true)
                {
                    NetworkStream stream = new NetworkStream(socket);
                    StreamReader streamRead = new StreamReader(stream);
                    StreamWriter streamWrite = new StreamWriter(stream);
                    try
                    {
                        streamWrite.WriteLine("Incoming message: " + streamRead.ReadLine());
                        streamWrite.Flush();
                    }
                    catch (Exception)
                    {
                        label1.Text = "Server is being shutdown";
                        return;
                    }
                }
            }
            socket.Close();
        }
    

    /// Client Code:

    public TcpClient client;
    NetworkStream stream;
    StreamReader streamRead;
    StreamWriter streamWrite;

        private void button1\_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("192.168.1.6", 1234);
            }
            catch (Exception)
            {
                MessageBox.Show("Not Connected");
            }
            stream = client.GetStream();
            streamRead = new StreamReader(stream);
            streamWrite = new StreamWriter(stream);
    
            try
            {
                streamWrite.WriteLine(textBox1.Text);
                streamWrite.Flush();
                string line = streamRead.ReadLine();
                MessageBox.Show("Message from server: " + line);
            }
            catch (Exception)
            {
                MessageBox.Show("Connection error");
            }
            streamWrite.Close();
            streamRead.Close();
            stream.Close();
        }
    
    N L E 3 Replies Last reply
    0
    • T teknolog123

      hi, I'm using below code for a basic client/server communication. I send a string to server and server sends it back to client with no problem. But I can do this only once and then connection goes, what should I do to be able to send more strings one after other without loosing the connection? Thanks in advance /// Server Code:

      private void button1_Click(object sender, EventArgs e)
      {
      TcpListener tcpListen = new TcpListener(IPAddress.Parse("192.168.1.6"), 1234);
      tcpListen.Start();
      Socket socket = tcpListen.AcceptSocket();

              if (socket.Connected)
              {
                  while (true)
                  {
                      NetworkStream stream = new NetworkStream(socket);
                      StreamReader streamRead = new StreamReader(stream);
                      StreamWriter streamWrite = new StreamWriter(stream);
                      try
                      {
                          streamWrite.WriteLine("Incoming message: " + streamRead.ReadLine());
                          streamWrite.Flush();
                      }
                      catch (Exception)
                      {
                          label1.Text = "Server is being shutdown";
                          return;
                      }
                  }
              }
              socket.Close();
          }
      

      /// Client Code:

      public TcpClient client;
      NetworkStream stream;
      StreamReader streamRead;
      StreamWriter streamWrite;

          private void button1\_Click(object sender, EventArgs e)
          {
              try
              {
                  client = new TcpClient("192.168.1.6", 1234);
              }
              catch (Exception)
              {
                  MessageBox.Show("Not Connected");
              }
              stream = client.GetStream();
              streamRead = new StreamReader(stream);
              streamWrite = new StreamWriter(stream);
      
              try
              {
                  streamWrite.WriteLine(textBox1.Text);
                  streamWrite.Flush();
                  string line = streamRead.ReadLine();
                  MessageBox.Show("Message from server: " + line);
              }
              catch (Exception)
              {
                  MessageBox.Show("Connection error");
              }
              streamWrite.Close();
              streamRead.Close();
              stream.Close();
          }
      
      N Offline
      N Offline
      Not Active
      wrote on last edited by
      #2

      teknolog123 wrote:

      what should I do to be able to send more strings one after other without loosing the connection?

      Dah, How about not closing the socket. Of course, the connection is lost each time, you told it to do that. Create the connection outside of the button click event and don't close it until necessary.


      I know the language. I've read a book. - _Madmatt

      T 1 Reply Last reply
      0
      • T teknolog123

        hi, I'm using below code for a basic client/server communication. I send a string to server and server sends it back to client with no problem. But I can do this only once and then connection goes, what should I do to be able to send more strings one after other without loosing the connection? Thanks in advance /// Server Code:

        private void button1_Click(object sender, EventArgs e)
        {
        TcpListener tcpListen = new TcpListener(IPAddress.Parse("192.168.1.6"), 1234);
        tcpListen.Start();
        Socket socket = tcpListen.AcceptSocket();

                if (socket.Connected)
                {
                    while (true)
                    {
                        NetworkStream stream = new NetworkStream(socket);
                        StreamReader streamRead = new StreamReader(stream);
                        StreamWriter streamWrite = new StreamWriter(stream);
                        try
                        {
                            streamWrite.WriteLine("Incoming message: " + streamRead.ReadLine());
                            streamWrite.Flush();
                        }
                        catch (Exception)
                        {
                            label1.Text = "Server is being shutdown";
                            return;
                        }
                    }
                }
                socket.Close();
            }
        

        /// Client Code:

        public TcpClient client;
        NetworkStream stream;
        StreamReader streamRead;
        StreamWriter streamWrite;

            private void button1\_Click(object sender, EventArgs e)
            {
                try
                {
                    client = new TcpClient("192.168.1.6", 1234);
                }
                catch (Exception)
                {
                    MessageBox.Show("Not Connected");
                }
                stream = client.GetStream();
                streamRead = new StreamReader(stream);
                streamWrite = new StreamWriter(stream);
        
                try
                {
                    streamWrite.WriteLine(textBox1.Text);
                    streamWrite.Flush();
                    string line = streamRead.ReadLine();
                    MessageBox.Show("Message from server: " + line);
                }
                catch (Exception)
                {
                    MessageBox.Show("Connection error");
                }
                streamWrite.Close();
                streamRead.Close();
                stream.Close();
            }
        
        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        ... and when you close a Socket, you should dispose of it too. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read formatted code with indentation, so please use PRE tags for code snippets.


        I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


        1 Reply Last reply
        0
        • N Not Active

          teknolog123 wrote:

          what should I do to be able to send more strings one after other without loosing the connection?

          Dah, How about not closing the socket. Of course, the connection is lost each time, you told it to do that. Create the connection outside of the button click event and don't close it until necessary.


          I know the language. I've read a book. - _Madmatt

          T Offline
          T Offline
          teknolog123
          wrote on last edited by
          #4

          thanks but even if I don't close the socket and listener, it throws exception. I've tried many things but no success, I'll go on trying

          L 1 Reply Last reply
          0
          • T teknolog123

            thanks but even if I don't close the socket and listener, it throws exception. I've tried many things but no success, I'll go on trying

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #5

            the smart thing to do is to catch exceptions in a variable, say exc, and look at them using

            exc.ToString()

            ; that would tell you precisely what went wrong, and enable you to find an adequate cure. :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


            I only read formatted code with indentation, so please use PRE tags for code snippets.


            I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


            1 Reply Last reply
            0
            • T teknolog123

              hi, I'm using below code for a basic client/server communication. I send a string to server and server sends it back to client with no problem. But I can do this only once and then connection goes, what should I do to be able to send more strings one after other without loosing the connection? Thanks in advance /// Server Code:

              private void button1_Click(object sender, EventArgs e)
              {
              TcpListener tcpListen = new TcpListener(IPAddress.Parse("192.168.1.6"), 1234);
              tcpListen.Start();
              Socket socket = tcpListen.AcceptSocket();

                      if (socket.Connected)
                      {
                          while (true)
                          {
                              NetworkStream stream = new NetworkStream(socket);
                              StreamReader streamRead = new StreamReader(stream);
                              StreamWriter streamWrite = new StreamWriter(stream);
                              try
                              {
                                  streamWrite.WriteLine("Incoming message: " + streamRead.ReadLine());
                                  streamWrite.Flush();
                              }
                              catch (Exception)
                              {
                                  label1.Text = "Server is being shutdown";
                                  return;
                              }
                          }
                      }
                      socket.Close();
                  }
              

              /// Client Code:

              public TcpClient client;
              NetworkStream stream;
              StreamReader streamRead;
              StreamWriter streamWrite;

                  private void button1\_Click(object sender, EventArgs e)
                  {
                      try
                      {
                          client = new TcpClient("192.168.1.6", 1234);
                      }
                      catch (Exception)
                      {
                          MessageBox.Show("Not Connected");
                      }
                      stream = client.GetStream();
                      streamRead = new StreamReader(stream);
                      streamWrite = new StreamWriter(stream);
              
                      try
                      {
                          streamWrite.WriteLine(textBox1.Text);
                          streamWrite.Flush();
                          string line = streamRead.ReadLine();
                          MessageBox.Show("Message from server: " + line);
                      }
                      catch (Exception)
                      {
                          MessageBox.Show("Connection error");
                      }
                      streamWrite.Close();
                      streamRead.Close();
                      stream.Close();
                  }
              
              E Offline
              E Offline
              Erik Funkenbusch
              wrote on last edited by
              #6

              Where to start.. where to start. there's so much wrong with this code that it seems clear you haven't even a basic idea of how execution scopes work, or what happens when you leave a block of code. I'm not criticizing you, but you're lacking some fundamental knowledge here. First, in your "server" you click a button to start.. ok, but all your code is running within that button click event.. which will lock up your UI on the server until processing is finished. This is probably not what you have in mind for a long running connection. You will most likely have to create a worker thread to handle this code, which I won't go into detail about much here.. but something for you to research into. Next, you create new NetworkStream and StreamReader/Writer objects within your while loop. This is highly wasteful, and will likely cause a lot of problems. I believe that when the NetworkStream object is destroyed at the end of your while loop, it will close the socket that it's attached to unless you specify false for socket ownership in the constructor. So your first step would be to move those three lines to outside of your while loop (but inside the if statement), that will keep them around while you process things. Next, you need a way to tell when the socket has been closed. Certainly, your exception handler will do that, but it's not the "correct" way. ReadLine() returns null when the socket is closed. So you should change your code to exit the loop when ReadLine() returns null. Now on to the client. First, you will probably want to create a "connect" button and a "disconnect" button (or you can get fancy and use the same button for both). This will create the TcpClient connnection and leave it open. The close will close the connection. Then you button click will do nothing but send the text in your textbox. You may want to create a second textbox to display the output that comes back instead of using a MessageBox.

              -- Where are we going? And why am I in this handbasket?

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups