0% found this document useful (0 votes)
117 views1 page

Java Chat Server Implementation Code

This document describes a Java program that implements a simple instant messaging server. The IMServer class extends Thread and contains methods for broadcasting messages to all connected clients, including when a new client connects or disconnects. The main method creates a server socket that listens for new client connections and spawns a new IMServer thread for each. Each IMServer instance reads incoming messages and broadcasts them to all other clients.

Uploaded by

hj43us
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
117 views1 page

Java Chat Server Implementation Code

This document describes a Java program that implements a simple instant messaging server. The IMServer class extends Thread and contains methods for broadcasting messages to all connected clients, including when a new client connects or disconnects. The main method creates a server socket that listens for new client connections and spawns a new IMServer thread for each. Each IMServer instance reads incoming messages and broadcasts them to all other clients.

Uploaded by

hj43us
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 1

Archivo: Documento 1 no guardado Página 1 de 1

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

class IMServer extends Thread {


Scanner in;
PrintWriter out;
static ArrayList<PrintWriter> pool = new ArrayList<PrintWriter>();

public IMServer(Socket s) throws IOException {


in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream(),true);
pool.add(out);
start();
}

public static void main(String args[]) throws IOException {


ServerSocket ss = new ServerSocket(7777);
while(true) new IMServer(ss.accept());
}

public void broadcast(String l ) {


for(PrintWriter output : pool)
if ( !output.equals(out) ) output.println(l);
}

public void run() {


broadcast("NEW CLIENT");
try {
while(true) {
String line = in.nextLine();
if (line.equalsIgnoreCase("quit")) break; else broadcast(line);
}
} catch (Exception e) {}
pool.remove(out);
out.close();
broadcast("CLIENT GONE");
}
}

You might also like