Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Does anyone have a socket sample that works?

Status
Not open for further replies.

scripter73

Programmer
Apr 18, 2001
421
US
I'm learning sockets. I have gone through I don't know how many socket tutorials, all offering advice on how to connect to a server through a "socket". I can't get any of them to work. Does anyone have a full-proof code where I can just see this work? It always seems that the ip addresses/url provided are out of date, etc. Here's the latest that doesn't work:

import java.io.*; // These two are needed for socket support
import java.net.*;

public class Client
{
public static void main(String args[])
{
try
{
Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

String line;
while(( line = in.readLine()) != null)
System.out.println(line);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}


Any help's appreciated.


Change Your Thinking, Change Your Life.
 
You don't need to be connected to the internet in oreder to play around with Sockets ... you can use 'localhost' to demonstrate the use of these classes ... but in order to get a Socket to connect, you need a ServerSocket to be listening for incoming connections ... else you won't get anywhere. Below is an example of a very simple ServerSocket, that sits listening on localhost port 1234 for incoming connections, and reports when they are recieved. The main class does the listening and then the inner class extends Thread, and handles each request - thus enabling multiple connections. This ServerSocket will keep listening for connections ontil you kill it by Ctrl-C or whatever.

Also below is a client Socket class, which lives only long enough to make a connection to the ServerSocket, sends a message, and then dies.

Hope this helps,

Ben

Code:
///////////////the server side code //////////////////////////////////////////////////////////////////

import java.net.*;
import java.io.*;
import java.util.*;

public class ServerSocketExample {
  public static int port;

  public void startConnection() {
      try {
        ServerSocket ss = new ServerSocket(port);
         while ( true ) {
            new ServerConnection(ss.accept()).start();
        }
      }
      catch (IOException e) {
          System.out.println("Broken http - " +e.toString());
      }
  }

  public static void main(String argv[]) throws IOException {
	Date date = new Date();
	if (argv.length > 0) {
           port = Integer.parseInt(argv[0]);
	}
	else {
	   port = 1234;
	}

	ServerSocket ss = new ServerSocket(port);	
	System.out.println("\n" +date +" - Listening on port : " +port);

        while (true)
            new ServerConnection(ss.accept()).start();
  }
}

/* inner class : ******************************************************************************/
class ServerConnection extends Thread {
  Date date;
  Socket client;
  ServerConnection ( Socket client ) throws SocketException {
    date = new Date();
    this.client = client;
    setPriority( NORM_PRIORITY - 1 );
  }

  public void run() {
     try {
   	System.out.println("\n" +date +" - Processing Socket Connection Thread : " +client);
   	BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(  ), "8859_1" ));
   	String request = in.readLine();
   	System.out.println("\n" +date +" - Data recieved from : " +client +"\n\t\t...data was : " +request );
	System.out.println("*****************************************************************************");
    }
    catch ( IOException e ) {
	System.out.println("Error on ServerSocket : " +e.toString());
    }
  }
}




/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////and the client code : //////////////////////////


import java.net.*;
import java.io.*;

public class ClientSocketExample {
  public static int port;

  public static void main(String argv[]) {
      Socket client = null;

      if (argv.length > 0) {
         port = Integer.parseInt(argv[0]);
      }
      else {
	   port = 1234;
      }

      try {
        client = new Socket("localhost", port);
	OutputStream out = client.getOutputStream();
        PrintWriter pout = new PrintWriter(out, true);
        pout.write("Hello, I am a Client Socket : " +client);
        System.out.println("Sending a message now");
        pout.close();
        out.close();
      }
      catch (NullPointerException e) {
        System.out.println("\nNullPointerException connecting to Socket... " +e.toString());
      }
      catch (UnknownHostException e) {
        System.out.println("\nUnknownHostException connecting to Socket... " +e.toString());
      }
      catch (IOException e) {
        System.out.println("\nIOException connecting to Socket... " +e.toString());
      }
  }
}
 
Thanks so much for your help, sedj. I'll try this and let you know.

Thanks again.
scripter73
Change Your Thinking, Change Your Life.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top