Results 1 to 19 of 19
  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default creating a socket and connecting to host

    i am working on creating an application that does texting, and was also thinking of integrating texting with it. i was having issues creating a socket, and locating the host though. here are my classes:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.io.IOException;
    import java.net.ServerSocket;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    
    public class SocketThirdServer extends JFrame{
    
       JLabel label = new JLabel("Text received over socket:");
       JPanel panel;
       JTextArea textArea = new JTextArea();
       ServerSocket server = null;
    
       SocketThirdServer(){ //Begin Constructor
         panel = new JPanel();
         panel.setLayout(new BorderLayout());
         panel.setBackground(Color.white);
         getContentPane().add(panel);
         panel.add("North", label);
         panel.add("Center", textArea);
       } //End Constructor
    
       public void listenSocket(){
    	    try{
    	      server = new ServerSocket(4444); 
    	    } catch (IOException e) {
    	      System.out.println("Could not listen on port 4444");
    	      System.exit(-1);
    	    }
    	    while(true){
    	      ClientWorker w;
    	      try{
    	        w = new ClientWorker(server.accept(), textArea);
    	        Thread t = new Thread(w);
    	        t.start();
    	      } catch (IOException e) {
    	        System.out.println("Accept failed: 4444");
    	        System.exit(-1);
    	      }
    	    }
    	  }
    
    	  protected void finalize(){
    	//Objects created in run method are finalized when 
    	//program terminates and thread exits
    	     try{
    	        server.close();
    	    } catch (IOException e) {
    	        System.out.println("Could not close socket");
    	        System.exit(-1);
    	    }
    	  }
    
    	  public static void main(String[] args){
    	        SocketThirdServer frame = new SocketThirdServer();
    		frame.setTitle("Server Program");
    	        WindowListener l = new WindowAdapter() {
    	                public void windowClosing(WindowEvent e) {
    	                        System.exit(0);
    	                }
    	        };
    	        frame.addWindowListener(l);
    	        frame.pack();
    	        frame.setVisible(true);
    	        frame.listenSocket();
    	  }
    	}
    Java Code:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    
    import javax.swing.JTextArea;
    
    public class ClientWorker implements Runnable {
    	private Socket client;
    	private JTextArea textArea;
    
    	ClientWorker(Socket client, JTextArea textArea) {
    		this.client = client;
    		this.textArea = textArea;
    	}
    
    	public void run() {
    		String line;
    		BufferedReader in = null;
    		PrintWriter out = null;
    		try {
    			in = new BufferedReader(new InputStreamReader(
    					client.getInputStream()));
    			out = new PrintWriter(client.getOutputStream(), true);
    		} catch (IOException e) {
    			System.out.println("in or out failed");
    			System.exit(-1);
    		}
    
    		while (true) {
    			try {
    				line = in.readLine();
    				// Send data back to client
    				out.println(line);
    				textArea.append(line);
    			} catch (IOException e) {
    				System.out.println("Read failed");
    				System.exit(-1);
    			}
    		}
    	}
    }
    i am using eclipse at the moment, and have been getting this error: "Could not listen on port 4444"

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    What statement gives the error?
    Can you post the full text of the error message?

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    It's your stupid message that is being printed out.

    You must call the printStackTrace method in ALL catch blocks so that you get the correct error message.

  4. #4
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    i got this code to work. it popped up the window to receive the text from the client. the only problem now, is that i am trying to get my client set up. here is the code that i have thus far:

    Java Code:
    import java.io.*;
    import java.net.*;
     
    public class KnockKnockClient {
        public static void main(String[] args) throws IOException {
     
            Socket kkSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;
     
            try {
                kkSocket = new Socket("taranis", 4444);
                out = new PrintWriter(kkSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
            }
     
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
     
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye."))
                    break;
                 
                fromUser = stdIn.readLine();
            if (fromUser != null) {
                    System.out.println("Client: " + fromUser);
                    out.println(fromUser);
            }
            }
     
            out.close();
            in.close();
            stdIn.close();
            kkSocket.close();
        }
    }
    and of course, i changed the "taranis" to my computer host name (myname-PC).

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    I see you need to add a call to printStackTrace() in your catch blocks.

    What problems are you having with this code?

  6. #6
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    i did it in the client code where the error message is printing out, but it it tells me that it cannot get the I/O for the connection to the host computer.

    here is the code:

    Java Code:
    try {
                kkSocket = new Socket("name-PC", 4444);
                out = new PrintWriter(kkSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
    e.printStackTrace();
                System.exit(1);
                    
            }
    i ran this code, and this is what i get:
    creating a socket and connecting to host-error.png
    Last edited by droidus; 12-12-2011 at 06:49 PM.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    Move the call to printStackTrace to before the call to exit().
    When you exit the JVM, NOTHING else will be executed

  8. #8
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    yea, sorry i saw that just when i finished posting it.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    Why do you expect the connection to be made? A refusal is a valid return if the host you are trying to connect to doesn't want to talk to you.

  10. #10
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    i made sure that the program was running on my host computer, so i am not sure as to why it wouldn't be able to talk to it

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    Have you tried debugging the code using the localhost address on one machine so you can verify that everything is working as you want it to?

  12. #12
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    hm, not sure how to do that. are you saying the host/client could be all on the same computer?

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    Yes, using the localhost address is the way to test the early versions of client/server programs.
    Look up the addresses: localhost or 127.0.0.1

  14. #14
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    how do i run the two class files at once?

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    I create a new testing class. In its main method I call the server and the client:
    Java Code:
       public static void main(final String[] args) {
         Thread t = new Thread(new Runnable() {
           public void run() {
               SocketThirdServer.main(args);  // Start the server
           }
         });
         t.start();
         try{
             Thread.sleep(50);  // let the server get started 
             KnockKnockClient.main(args);  // Start the client
          }catch(Exception x){
             x.printStackTrace();
          };
       }

  16. #16
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    alright, so it seems to run without any issues. i am not sure what i do with the client end though. shouldn't i be able to enter text somewhere, which gets sent the the host? i notice in the knockknockclient class, this code:

    Java Code:
    while ((fromServer = in.readLine()) != null)
    do i enter this in the console area? it doesn't seem to do anything? the text should pop up in the host jpanel, right?

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    seems to run without any issues.
    What does the code do when you execute it?
    What do you want it to do?
    shouldn't i be able to enter text somewhere, which gets sent the the host
    Ask the author of the program about how it is supposed to work.
    the text should pop up in the host jpanel, right?
    Look at the code to see what it is supposed to do or ask the author.

  18. #18
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: creating a socket and connecting to host

    when it runs, i would like to have the computers talk (or chat in this instance) with each other.

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: creating a socket and connecting to host

    Try debugging your code by adding printlns to find out where the code is hanging. By adding enough printlns you should be able to see the statement(s) where the code is hanging. When you see where the code is hung, it should give you some ideas on how to fix the code.

Similar Threads

  1. How to create file into another host from a host
    By varadha in forum Networking
    Replies: 3
    Last Post: 02-10-2010, 10:03 PM
  2. copy file from local host to remote host
    By isotoper in forum New To Java
    Replies: 4
    Last Post: 12-24-2009, 05:41 PM
  3. Creating Socket
    By ersachinjain in forum Networking
    Replies: 1
    Last Post: 11-18-2009, 11:10 PM
  4. Creating Socket Issue
    By castiel in forum Networking
    Replies: 2
    Last Post: 08-25-2009, 02:34 PM
  5. Replies: 0
    Last Post: 10-31-2008, 08:07 PM

Posting Permissions

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