❮ Previous Next ❯

Creating a Server

We can write a socket that can be used to connect a server and a client. Once the socket is created, the server can send data to the client and the client can receive it. All we have to do is to just send the data from the server to the socket. The socket will take care of whom to send the data on the network. Let us follow these steps to create a server that sends some strings (messages) to the client.

ServerSocketss=new ServerSocket(777); Socket s=ss.accept();              OutputStreamobj=s.getOutputStream(); PrintStreamps=new PrintStream(obj); ps.println(str); ss.close(); // close ServerSocket
p.close(); // close Socket
ps.close(); // close PrintStream Program:
//Write a program to create a server to send some strings(message) to the client.
import java.io.*;
import java.net.*;
classAlok
{
            public static void main(String args[])throws Exception
            {
                        // Create a server socket with some socket number
                        ServerSocket=new ServerSocket(777);
                        // let the ServerSocket wait till a client accepts connection
                        Socket s=ss.accept();
                        System.out.println(“Connection Established”);
                        // attach Output Stream to the server socket
                        OutputStreamobj=s.getOutputStream();
                        // attach print stream to send data to the socket
                        PrintStreamps=new PrintStream(obj);
                        // send 2 strings to the client
                        String str=”Hello client”;
                        ps.println(str);
                        ps.println(“Bye”);
                        // close connection by closing the streams and sockets
                        ps.close();
                        ss.close();
                        s.close();
}
}
Output:
            D:\my java>javac Alok.java
            D:\my java>
            DO NOT RUN THIS PROGRAM TILL THE CLIENT IS ALSO CREATED...

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved