Can a client also be a server, socket/serversocket

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • brendanmcdonagh
    New Member
    • Nov 2007
    • 153

    Can a client also be a server, socket/serversocket

    Hi,

    i have created my own messaging program which entails basically having a application with a serversocket listening for connections and then does it's thing when it receives a connectin from the client socket.

    My question is how would i have both listening rather than having to have a client/server scenario so that either can be woken (server) and either can start conversation (client).

    Regards

    Brendan
  • myusernotyours
    New Member
    • Nov 2007
    • 188

    #2
    Hi,

    Just have a thread that listens and another that makes a connection. i.e have a ServerSocket in one thread and a Socket in the other.

    If you don't know how to do threading, you can google for java concurrency. The Threading API is pretty easy to use.

    Regards,

    Alex.

    Comment

    • brendanmcdonagh
      New Member
      • Nov 2007
      • 153

      #3
      cheers for that. funnily enough i am just about to read abouthreads.

      So i have an app that is capable of being a server an creating a socket when .accept() or making a connection if user chooses it to be a client, and this is done by user starting a thread by there choice.

      So a conditional statement is needed if(server.accep t())
      {
      do this
      }


      although i know that method doesn't return a boolean but a socket, so can any one offer me a direction on this matter please?

      Regards

      brendan

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by brendanmcdonagh
        cheers for that. funnily enough i am just about to read abouthreads.

        So i have an app that is capable of being a server an creating a socket when .accept() or making a connection if user chooses it to be a client, and this is done by user starting a thread by there choice.

        So a conditional statement is needed if(server.accep t())
        {
        do this
        }


        although i know that method doesn't return a boolean but a socket, so can any one offer me a direction on this matter please?
        That's just programming; if you'd read the API documentation for ServerSocket
        you'd know that the accept() method only returns when a client has successfully
        connected to the server, so:

        Code:
        Socket client= serverSocket.accept();
        serve(client);
        There is no condition; simply serve the client (in another thread).

        kind regards,

        Jos

        Comment

        • brendanmcdonagh
          New Member
          • Nov 2007
          • 153

          #5
          thanks for your help jos, im confused though mate and i have read serversocket and socket api on numerous occasions this week, first by what you mean by serve(client) and also by the following , it's ok waiting for a connection and getting it to do an action when .accept() is executed but what if the class that is currently a serversocket(li stener) wanted to initiate a connection, so in other words it also has the ability to initiate a connection rather than just do something when a connection is initiated with it. So the only way i can understand it at the moment is integrating the client code i have with the server code on both computers i have.

          I really hope you understand what im trying to do and can offer me a way to understand how to do it, how can i say it... It's not a code issue it's a design issue if that makes sense.

          regards

          Brendan

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by brendanmcdonagh
            I really hope you understand what im trying to do and can offer me a way to understand how to do it, how can i say it... It's not a code issue it's a design issue if that makes sense.
            Suppose you and I have to talk to each other; we each take turns so one of us
            has to start talking. It's just an agreement, we can't just both wait until the other
            one starts talking and we can't just start talking. We have to follow a certain protocol.
            The party who starts the talking is the client, the other one is the server. The client
            has to make him/itself known to the server. It's all just an agreement. Of course
            a server can also be a client w.r.t. other servers and vice versa.

            kind regards,

            Jos

            Comment

            • brendanmcdonagh
              New Member
              • Nov 2007
              • 153

              #7
              Jos, you have helped on many occasions and i appreciate your help and with you reading my posts i hope you know i have never wanted someone just to do it for me but w.r.t your last thread,

              please tell me how?

              I'll post my client code because by the sounds of the messages it's a case of a couple of lines of code

              Code:
              /* 
               * Main.java 
               * 
               * Created on 28 October 2008, 13:19 
               * 
               * To change this template, choose Tools | Options and locate the template under 
               * the Source Creation and Management node. Right-click the template and choose 
               * Open. You can then make changes to the template in the Source Editor. 
               */ 
                
              package clientside; 
                
              import java.io.*; 
              import java.net.*; 
              import java.util.*; 
              import javax.swing.*; 
              import java.awt.*; 
              import java.awt.event.*; 
                
                
              public class Main implements ActionListener 
              { 
                  public static JFrame aFrame; 
                  public static JButton aButton; 
                  public static JButton aButton2; 
                  public static JTextField inputArea; 
                  public static JTextArea output; 
                
                  static ServerSocket server; 
                  static Socket socket; 
                  static PrintStream outStream; 
                  static BufferedReader inStream; 
                  static String aName;
                  static String address;
                  static int port;
                  
                  
                
                  public Main() 
                  { 
              aFrame = new JFrame(); 
              aFrame.setSize(500, 500); 
              aFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
              aFrame.setTitle("Input your message"); 
              aFrame.setLayout(new BorderLayout()); 
              
              aFrame.setVisible(true); 
                
              aButton = new JButton(); 
              aButton.setText("Press to send message"); 
              aButton.setSize(200, 25); 
              aButton.addActionListener(this); 
              aFrame.add(aButton, BorderLayout.NORTH); 
                
              
                
               inputArea = new JTextField(50); 
              inputArea.setVisible(true); 
              inputArea.addActionListener(this);
              aFrame.add(inputArea, BorderLayout.SOUTH); 
                
              output = new JTextArea(25, 50); 
              output.setVisible(true); 
              aFrame.add(output, BorderLayout.CENTER);
              
                
                
                  } 
              public static void main(String[] args) 
              { 
              try 
              {     
                  Main aMain = new Main();
                  
                  aName = JOptionPane.showInputDialog(null, "Enter Your Name : ",
              "Input Box", 1);
                  address = JOptionPane.showInputDialog(null, "Enter IP or address : ",
              "Input Box", 1);
                  String aPort = JOptionPane.showInputDialog(null, "Enter port to connect through : ",
              "Input Box", 1);
                  port = Integer.parseInt(aPort);
                  
                  
                   socket = new Socket(address, port); 
                  inStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
                  outStream = new PrintStream(socket.getOutputStream()); 
                 
                  
                  
                  String line;
              
                    while  (!(line = inStream.readLine()).equals("exit") )
                    {
                      Main.output.append (line + '\n');
                      
                    }
                  
                   socket.close();
              } 
              catch (Exception anException) 
              { 
                  System.out.println("Error: " + anException); 
              } 
              } 
              public void actionPerformed(ActionEvent e) 
              { 
                  String aString = Main.inputArea.getText();
                  if((e.getSource() == aButton) || (e.getSource() == inputArea))
                  {
               
                  if((aString.equals("exit")) || (aString.equals(" exit")))
                      { 
                          
                          
                          try
                          {
                              
                              System.exit(1);
                              socket.close();
                          }
                          catch(Exception anException)
                          {
                              
                          }
                      } 
                  else 
                  { 
                      Main.output.append (aName + " says " + aString + '\n');
                      Main.inputArea.setText(" ");
                      Main.outStream.println(aName + " says " + aString); 
                      
                      
                  } 
              }
              }
              
              
              }
              How can i make this listen and do something when a connection is made to it or if a user decides to, connect to a server and do something (what it currently does)?

              Regards

              Brendan

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by brendanmcdonagh
                How can i make this listen and do something when a connection is made to it or if a user decides to, connect to a server and do something (what it currently does)?
                Simply use another thread again that manages the accept()s.

                kind regards,

                Jos

                Comment

                • brendanmcdonagh
                  New Member
                  • Nov 2007
                  • 153

                  #9
                  ok, will do. thank you jos

                  Brendan

                  Comment

                  Working...