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-
[java]
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);}
}
}
[/java]
- Client-
[java]
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);}
}
}
[/java]
Note-
To check the programs,simultaneously run both the programs.