A Simple Server

The task is to construct a simple server which just passes a string to the client.

Client/server describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request. Although the client/server idea can be used by programs within a single computer, it is a more important idea in a network.
A server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
InputStream and OutputStream are used to transfer of data between server and client.

java.net includes Socket and ServerSocket classes.
java.io includes DataOutputStream and DataInputStream classes.

    Server-

 

 

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

public class server {

    public static void main(String[] args) {
        try{
        ServerSocket s=new ServerSocket(1254); //same port number
        Socket s1=s.accept(); //accepts the connection
        OutputStream stout=s1.getOutputStream();
        DataOutputStream dos=new DataOutputStream(stout);
        dos.writeUTF("HELLO WORLD");
        dos.close();
        s1.close();
        }
        catch(Exception e)
        {System.out.println(""+e);}

    }

}
    Client-

 

 

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

public class client {
    public static void main(String[] args) {
        try{
            Socket s= new Socket("localhost",1254);//localhost or any other IP
            InputStream sin=s.getInputStream();
            DataInputStream din=new DataInputStream(sin);
            String str=new String(din.readUTF());
            System.out.println(""+str);
            din.close();
            sin.close();
            s.close();
        }
        catch(Exception e)
        {System.out.println(""+e);}
        }
}


Note-

To check the programs,simultaneously run both the programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

44,547 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>