Java I/O and NIO.2

Sockets programming in Java: A tutorial

Write your own client/server applications seamlessly in Java

Java I/O and NIO.2

Show More
1 2 Page 2
Page 2 of 2
import java.io.*;
import java.net.*;
public class echo3 {
    public static void main(String args[]) {
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
        ServerSocket echoServer = null;
        String line;
        DataInputStream is;
        PrintStream os;
        Socket clientSocket = null;
// Try to open a server socket on port 9999
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
        try {
           echoServer = new ServerSocket(9999);
        }
        catch (IOException e) {
           System.out.println(e);
        }   
// Create a socket object from the ServerSocket to listen and accept 
// connections.
// Open input and output streams
    try {
           clientSocket = echoServer.accept();
           is = new DataInputStream(clientSocket.getInputStream());
           os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
           while (true) {
             line = is.readLine();
             os.println(line); 
           }
        }   
    catch (IOException e) {
           System.out.println(e);
        }
    }
}

Conclusion

Programming client/server applications is challenging and fun, and programming this kind of application in Java is easier than doing it in other languages, such as C. Socket programming in Java is seamless.

The java.net package provides a powerful and flexibile infrastructure for network programming, so you are encouraged to refer to that package if you would like to know the classes that are provided.

Sun.* packages have some good classes for networking, however you are not encouraged to use those classes at the moment because they may change in the next release. Also, some of the classes are not portable across all platforms.

Qusay H. Mahmoud is a graduate student in computer science at the University of New Brunswick, Saint John campus, Canada. He is currently working on his master's thesis as well as teaching a computer science course at the University. His thesis concentrates on the Web and Java, and the results of his thesis will be available online as soon as he is finished. He has been working with Java since it was released to the public.

Learn more about this topic

1 2 Page 2
Page 2 of 2