Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views

IMServer Java

This document contains the code for an IMServer class written in Java. The IMServer class extends the Thread class and runs a server on port 7777 that accepts incoming client connections and broadcasts messages between all connected clients. When a new client connects, it is added to a pool of PrintWriters and its messages are broadcast to all other clients. When a client disconnects, it is removed from the pool.

Uploaded by

hj43us
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
52 views

IMServer Java

This document contains the code for an IMServer class written in Java. The IMServer class extends the Thread class and runs a server on port 7777 that accepts incoming client connections and broadcasts messages between all connected clients. When a new client connects, it is added to a pool of PrintWriters and its messages are broadcast to all other clients. When a client disconnects, it is removed from the pool.

Uploaded by

hj43us
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 1

Archivo: /home/misan/workplace/IMServer/IMServer.

java 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 ) {


synchronized (pool) { for(PrintWriter output : pool) // NEW HERE
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) {System.out.println("Exception "+e);}
synchronized (pool) {pool.remove(out);} // NEW HERE
out.close();
broadcast("CLIENT GONE");
}
}

You might also like