Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

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.

  • • At server side, create a server socket with some port number. This is done using ServerSocket class as: ServerSocketss=new ServerSocket(777);
  • • Now, we should make the server wait till a client accepts connection. This is done using accept() method. Socket s=ss.accept();
  • • Attach output string to the server socket using getOutputStream() method. This method returns OutputStream object. This stream is used by the socket to send data to client. OutputStreamobj=s.getOutputStream();
  • • Take another stream like PrintStream to send data till the socket. PrintStreamps=new PrintStream(obj);
  • • Finally the PrintStream is used by the server to send data to the client. To send data we have print() or println() methods available in PrintStream. ps.println(str);
  • • Then close the connection. This can be done by closing all the streams and sockets at server side as:

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...

About the Author



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






 PreviousNext