View RSS Feed

My Java Tips

Socket Programming (Server)

Rate this Entry
by , 11-09-2011 at 06:14 PM (756 Views)
Socket programming is easy and fun. In this post, I will create a simple Socket Server that will listen on a post for client requests. It will get data from the client and will send the acknowledgment.


First step is to declare a server socket, a client socket and input/output streams. I assume that you are familiar with streams. Then we have to open a connection on a port. Usually it is not a wise decision to use port number that is less than 1023 because ports less than 1023 are reserved of OS use. We will create a SeverSocket object and will specify port on which that ServerSocket will be opened. Once we have the ServerSocket object, we will create a client socket object that will wait for the client’s request.

Java Code:
clientSocket = echoServer.accept();
Once the connection is made, streams will be initialized and data transfer can take place. We are trying to get data from user and then simply send connection date/time to the client. I know it doesn’t make sense, but you can send any thing back to the client. This is just an example.

Java Code:
        ServerSocket echoServer = null;
        String line;
        DataInputStream is;
        PrintStream os;
        Socket clientSocket = null;

        try {
           echoServer = new ServerSocket(2222);
        }
        catch (IOException e) {
           System.out.println(e);
        }  

    try {
        System.out.println("Waiting for the client request ... ");
    	clientSocket = echoServer.accept();
    	System.out.println("Request received.");
           is = new DataInputStream(clientSocket.getInputStream());
           os = new PrintStream(clientSocket.getOutputStream());

           os.println("Hi. You connected to the Server at: " + new Date()); 

           while (true) {
             line = is.readLine();
           System.out.println("Client: "+line);
             os.flush();
           }
        }
    catch (IOException e) {
          e.printStackTrace();
        }
If the port you are using is already in use, you will get following error:


java.net.BindException: Address already in use: JVM_Bind

The Socket Server will keep on waiting for the connections and will send and receive the data. It is very interesting to use such servers on a network.

Submit "Socket Programming (Server)" to Facebook Submit "Socket Programming (Server)" to Digg Submit "Socket Programming (Server)" to del.icio.us Submit "Socket Programming (Server)" to StumbleUpon Submit "Socket Programming (Server)" to Google

Updated 11-09-2011 at 06:28 PM by Java Tip

Tags: None Add / Edit Tags
Categories
Network Programming

Comments