TCP/IP SOCKET APPLICATION
// BROADCAST
// SERVER PROGRAM
import java.io.*;
import java.net.*;
class sock
{
Socket
s[] = new Socket[20];
int
cnt=0;
}
class cthd extends Thread
{
Socket
s1;
String
str;
BufferedReader
in;
PrintWriter
out;
int
cnt;
sock
so;
cthd(
sock p1, int i)
{
s1
= p1.s[i];
cnt=i;
so=p1;
start();
}
public
void run()
{
try
{
in
= new BufferedReader(new InputStreamReader(s1.getInputStream()));
for(int
l=0;l<cnt;l++)
{
out
= new PrintWriter(new BufferedWriter(new
OutputStreamWriter(so.s[l].getOutputStream())),true);
out.println("the
client number " +cnt+" has logged in");
}
while(true)
{
str=in.readLine();
for(int
i=0; i<so.cnt;i++)
{
out
= new PrintWriter(new BufferedWriter(new
OutputStreamWriter(so.s[i].getOutputStream())),true);
if(str.equalsIgnoreCase("exit"))
{
if(i==cnt)
out.println(str);
else
out.println("Client
number " +cnt+ ":"+str+"\n"+" the client number"+cnt+"has logged out");
}
else
out.println("Client
number" +cnt+":"+str);
}
}
}
catch(Exception
e)
{
}
}
}
public class BroadcastServer
{
public
static void main(String a[]) throws Exception
{
ServerSocket
ss = new ServerSocket(3000);
sock
so = new sock();
while(true)
{
so.s[so.cnt]
= ss.accept();
new
cthd(so,so.cnt++);
}
}
}
// BROADCAST
// CLIENT PROGRAM
import java.io.*;
import java.net.*;
class Reader extends Thread
{
Socket
s;
public
Reader(Socket s1)
{
s
= s1;
start();
}
public
void run()
{
try
{
BufferedReader
i = new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true)
{
String
str = i.readLine();
System.out.println(str);
}
}
catch(Exception
e)
{
}
}
}
class Writer extends Thread
{
Socket
s;
public
Writer(Socket s1)
{
s
= s1;
start();
}
public void run()
{
try
{
PrintWriter
o = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
BufferedReader
i = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String
str = i.readLine();
o.println(str);
if(str.equalsIgnoreCase("exit"))
{
s.close();
break;
}
}
}
catch(Exception
e)
{
}
}
}
class BroadcastClient
{
public
static void main(String a[]) throws Exception
{
try
{
Socket
s;
s
= new Socket(InetAddress.getLocalHost(),3000);
new
Reader(s);
new
Writer(s);
}
catch(Exception
e)
{
}
}
}
/*
Execution.
First compile and execute the server.
Open 2 or more client windows and connect
to the server.
When a client connects to the server, the
server informs all the other connected clients about the new login.
When a client sends messages, the server
broadcasts to all client windows.
Type 'exit' to terminate the client window.
*/
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu