Sockets - Networks with Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    Sockets - Networks with Java

    Since the opening of the Internet to the public in 1989, networks and their meaning to all of us have grown with an astonishing rate. Today, many people can't imagine a world without the Internet offering more information than one human could ever learn in a lifetime, gigantic improvements on many areas of software (e.g. automatic updates, posting bug reports etc.) and more forms of communication than ever existed before. Naturally, many programmers ask themselves at some point: How can I use this?
    For many uses, such as connection via HTTP and FTP, libraries have been developed for Java, that offer a wide range of functions. But if you don't want HTTP or FTP, what can you use?

    The answer is simple: In Java, both HTTP and FTP use the native classes Socket and ServerSocket. These are used to make very basic connections - what happens then, depends on the rest of the code. So, your Program can use them to download files, communicate with a database or even chat with other Computers!
    In this Howto, I'll explain how to create applications using these basic classes.
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Chapter 1
    Let's have a look at the description of ServerSocket and Socket:
    [code=java]
    public class ServerSocket extends Object
    // This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.
    [/code][code=java]
    public class Socket extends Object
    // This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.
    [/code]So, to visualize that, imagine the following:
    A ServerSocket is sitting around on Port x, waiting for something to happen. There comes a Socket to Port x, sees the ServerSocket and says: "Hi ServerSocket! Here's some data!"
    The ServerSocket replies with: "Oh, thank you. Let's have a look..." and does something with the data. Now it can (but doesn't have to) answer, for example by saying: "OK, the data is valid. Thanks again, Socket!"
    To find out, how this happens in reality, let's have another look at the ServerSockets API,
    First of all, the constructor. The one we're going to use is
    [code=java]ServerSocket(in t port)[/code]You can initialize the ServerSocket with a Port where it's supposed to wait for a Socket to contact it.[code=java]ServerSocket server = new ServerSocket(42 42); // Wait at Port 4242[/code]Then there's the method[code=java]Socket accept() // Listens for a connection to be made to this socket and accepts it[/code]So, if you type[code=java]Socket socket = null;
    socket = server.accept() ;[/code]it will wait, until a Socket it trying to make contact and then connects to that Socket.
    Now, we want to hear, what that Socket has to say. In the Socket API we find the Method[code=java]OutputStream getOutputStream () // Returns an output stream for this socket.[/code]Output looks good, doesn't it?
    OK, let's catch that OutputStream:[code=java]BufferedReader inStream = new BufferedReader(
    new InputStreamRead er(
    socket.getInput Stream()));[/code]This way, we can read more than one Bit a time.
    Now we'll want to do something with the received Info. How about printing it?[code=java]System.out.prin tln(inStream.re adLine());[/code]There, that was fun. But now we want to let the Socket go, so we use[code=java]socket.close();[/code]to do so.
    There. That's our first server! Let's just put it all together:
    [code=java]
    import java.net.Server Socket;
    import java.net.Socket ;
    import java.io.Buffere dReader;
    import java.io.InputSt reamReader;
    public class FirstServer
    {
    public static void main (String args[]) throws Exception
    {
    ServerSocket server = new ServerSocket(42 42);
    Socket socket = null;
    socket = server.accept() ;
    BufferedReader inStream = new BufferedReader(
    new InputStreamRead er(
    socket.getInput Stream()));
    System.out.prin tln(inStream.re adLine());
    socket.close();
    }
    }
    [/code]

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

      #3
      Chapter 2
      Now that we have a Server, we still need a Client to send something. So, let's start!
      First of all, we'll need a Socket. A quick look into the Socket API gives us an choice - we'll use[code=java]Socket(String host, int port) // Creates a stream socket and connects it to the specified port number on the named host.[/code]this time.
      As I assume, you'll be writing both the Server and the Client on the same machine for the time being, we'll simply use "localhost" as a host. And which Port? Oh yes, we used 4242 for the Server, so we should use the same one here.[code=java]Socket socket = new Socket("localho st", 4242);[/code]Next, we want to be able to send something to the host (= server). We'll limit us to Strings for the moment, so why not use a PrintStream?
      [code=java]PrintStream outStream = new PrintStream(
      socket.getOutpu tStream());[/code]Hey, that looks good! Let's try using it!
      [code=java]outStream.print ln("Hello World!");[/code]And don't forget to close that Socket![code=java]socket.close();[/code]There, that should be it!
      Here, let's put it all together:[code=java]
      import java.net.Socket ;
      import java.io.PrintSt ream;
      public class FirstClient {
      public static void main (String args[]) throws Exception
      {
      Socket socket = new Socket ("localhost" , 4242);
      PrintStream outStream = new PrintStream(soc ket.getOutputSt ream());
      outStream.print ln("Hello World!");
      socket.close();
      }
      }
      [/code]Just compile it (either with your IDE or by using javac FirstClient.jav a and javac FirstServer.jav a on the command line) and then start the Server, then in a separate window, the Client (again: use your IDE or type java FirstServer and, in a different window, java FirstClient).
      There, the Server printed "Hello World!", didn't it? And then both programs closed? Wonderful, that's your first ever Client-Server-Program in Java.

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        not part of the Article
        There, that's the first part done. Any suggestions, corrections or comments?

        I'll continue with sending the Signal back (Echo Server), then I guess I'll put both types of Sockets together, so that I have a little chat program. That will then be extended to multiple connections.
        Probably then I'll say a few words about sending something else than a string (with an example, I would guess) and that should be it.

        Constructive Criticism is always welcome! ^^

        Greetings,
        Nepomuk

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by nepomuk
          Constructive Criticism is always welcome! ^^
          I just read it and it looks fine to me (I'll fix a few small typos afterwards). I think
          people would really like to see a (sort of) full blown chat application. Be aware
          though that at least the server part is inherently multi-threaded (everybody types
          when s/he wants to) and the clients should be able to receive data from the
          server at the same time a use is typing his/her reply so I think some threading
          shows up the client code as well. Read the API documentation for the Selector
          class for starters (blocking for input on a single socket won't do it, but maybe
          I'm wrong). Success with the sequel of your article; note that your article has
          to be a one part article otherwise the second, third etc. parts show up as comment
          to the first part which looks silly.

          kind regards,

          Jos

          Comment

          • rpnew
            New Member
            • Aug 2007
            • 189

            #6
            Hi,

            I read your tut and i found it very good. I even tried it and its working perfectly. So looking forward to your further tutorials..

            Regards,
            RP

            Comment

            Working...