Broadcasting

 

Write a network program to broadcast a message from the server.

Server.java


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

class Server
{
	public static void main(String args[]) throws Exception
	{
		ServerSocket ss= new ServerSocket(7632);
		Socket s[]=new Socket[25];
		System.out.println("Enter the number of clients: ");
		BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
		String str=br.readLine();
		int n=Integer.parseInt(str);
		int i;
		System.out.println("Server is waiting for all the clients
to connect");
		for(i=0;i<n;i++)
		{
			s[i]=ss.accept();
		}
		System.out.println("All clients have connected.");
		System.out.println("Enter the data to be broadcasted");
		while(true)
		{
			str=br.readLine();
			for(i=0;i<n;i++)
			{
				PrintWriter pr= new PrintWriter(s[i]
.getOutputStream());
				pr.println(str);
			}
		}
	}
}

Client.java


import java.io.*;
import java.net.*;
class Client
{
	public static void main(String args[]) throws Exception
	{
		String str;
		Socket s=new Socket("localhost",7632);
		while(true)
		{
			BufferedReader br= new BufferedReader(new
InputStreamReader(s.getInputStream()));
			str=br.readLine();
			System.out.println("Server: "+str);
			if(str.equals("`"))
				break;
		}
		s.close();
	}
}

Output

 

Terminal 1 Terminal 2 Terminal 3
>java Server> Enter the number of clients: 2> Server is waiting for all the clients to connect

 

 

> All clients have connected.

> Enter the data to be broadcasted

>Hello

 

>World

 

 

 

 

>java Client

 

 

 

 

 

 

>Server: Hello

 

>Server: World

 

 

 

 

 

>java Client

 

 

 

 

 

>Server: Hello

 

>Server: World

 

 

Leave a Reply

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