chatter class
import java.io.*;
import java.net.*;
public class Chatter implements Runnable{
private Socket client;
private ChatterList counter;
private String chatter;
ChatterList chl = new ChatterList();
public Chatter(Socket c, ChatterList chl){
client = c;
counter = chl;
}
public void run(){
BufferedReader input = null;
PrintWriter output = null;
//next.connect(Chatter.this);
counter.addConnection();
try{
input = new BufferedReader
(new InputStreamReader
(client.getInputStream()));
output = new PrintWriter
(new OutputStreamWriter
(client.getOutputStream()));
output.println("Enter Your Name");
output.flush();
chatter = input.readLine();
output.println("Hello " + chatter);
output.flush();
String line;
boolean finish = false;
while (!finish){
line = input.readLine();
if ((line == null) || (line.trim().equals("BYE"))){
finish = true;
}
else if (line.trim().equals("END")){
ChatroomServer.shutDown();
return;
}
else if (line.equals("0s")) {
output.println("Connections: " +
counter.getConnections());
output.println("Currently : " +
counter.getCurrentConnections());
output.flush();
}
else{
output.println(chatter + ": " + line);
output.flush();
}
}
}
catch(IOException e){
System.err.println(e.getMessage());
}
finally{
counter.endSession();
try{
input.close();
}
catch(IOException e){
}
if (output != null){
output.close();
}
if (client != null){
try{
client.close();
}
catch(IOException e){
}
}
}
}
}
server class
import java.io.*;
import java.net.*;
public class ChatroomServer {
private static final int PORT_NUM = 8189;
private static ServerSocket ss;
private static boolean shutDownCall = false;
public static void shutDown(){
shutDownCall = true;
try{
ss.close();
}
catch (Exception e){
System.err.println("Problem shutting down:");
System.err.println(e.getMessage());
System.exit(1);
}
}
public static void main(String[] args) {
Socket incoming;
Thread t;
ChatterList chl = new ChatterList();
try{
ss = new ServerSocket(PORT_NUM);
while(true){
incoming = ss.accept();
t = new Thread(new Chatter(incoming, chl));
t.start();
}
}
catch(SocketException se){
if(! shutDownCall){
System.err.println("Socket problem:");
System.err.println(se.getMessage());
System.exit(1);
}
}
catch(IOException ioe){
System.err.println("I/O problem:");
System.err.println(ioe.getMessage());
System.exit(1);
}
finally{
if (ss != null){
try{
ss.close();
}
catch(Exception e){
System.err.println("closing:" + e.getMessage());
}
}
}
}
}
ChatterList class
public class ChatterList{
private int connections = 0;
private int currentConnections = 0;
private ChatterList chl = null;
public ChatterList(){
}
private void add(Chatter c){
theList = new ChatterNode(c, theList);
}
public void connect(Chatter c){
add(c);
}
public int getConnections() {
return connections;
}
public int getCurrentConnections() {
return currentConnections;
}
public void addConnection() {
connections++;
currentConnections++;
}
public void endSession() {
currentConnections--;
}
}

New Topic/Question
Reply



MultiQuote





|