01-01-2013, 12:21 PM
Implement a Distributed Chat Server using TCP Sockets
Implement a Distributed Chat Server using TCP Sockets.docx (Size: 12.44 KB / Downloads: 30)
DISTRIBUTED CHAT SERVER USING TCP SOCKETS
A chat server allows clients to broadcast messages to other clients that have joined in the chat session (called peers). The twist is that the chat server is effectively distributed among all the clients that are currently running, with a central server used mainly to bootstrap a client that wants to join the chat session, so that the client can find one (or several) other clients.
JAVA CODE
1) Server.java
import java.net.*; import java.io.*;
public class server { public static void main(String args[]) throws IOException
{ ServerSocket s1=null;
try { s1=new ServerSocket(98); }
catch(Exception e) { System.out.println("Port not found");
e.printStackTrace(); }
Socket c=null;
try { c=s1.accept();
System.out.println("Connection from"+c); }
catch(Exception e) { System.out.println("not accepted");
e.printStackTrace(); }
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReader in = new BufferedReader (new
InputStreamReader (c.getInputStream()));
String l;
BufferedReader sin = new BufferedReader (new
InputStreamReader (System.in));
System.out.println("I am ready type now");
while((l=sin.readLine())!=null) out.println(l);
out.close();
sin.close();
c.close(); s1.close();
}
}
2) Client.java
import java.net.*; import java.io.*;
public class Client { public static void main(String args[]) throws IOException
{ Socket s=null;
BufferedReader b=null;
try{ s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new InputStreamReader
(s.getInputStream())); }
catch(Exception e){ System.out.println("I do not host");
e.printStackTrace(); }
String inp;
while ((inp=b.readLine())!=null) System.out.println(inp);
b.close(); s.close();
}}