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.
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(); } }
D:\my java>javac Alok.java
D:\my java>
DO NOT RUN THIS PROGRAM TILL THE CLIENT IS ALSO CREATED...
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc