Created
February 2, 2015 07:50
-
-
Save revox/56bff246fd2204df8f8a to your computer and use it in GitHub Desktop.
Threaded broadcast server showing the use of shared data to maintain a list of clients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| import java.io.*; | |
| import java.net.*; | |
| class SynchList | |
| { | |
| ArrayList <OutputStream> it; | |
| SynchList() | |
| { | |
| it=new ArrayList <OutputStream> (); | |
| } | |
| synchronized OutputStream get(int i) | |
| { | |
| return it.get(i); | |
| } | |
| synchronized void add(OutputStream o) | |
| { | |
| it.add(o); | |
| } | |
| synchronized int size() | |
| { | |
| return it.size(); | |
| } | |
| } | |
| class broadcasterWithList | |
| { | |
| static SynchList Outputs = new SynchList(); | |
| static int i=0; | |
| public static void main(String[] argv) throws Exception | |
| { | |
| ServerSocket s = new ServerSocket(5000); | |
| Transaction k; | |
| while (true) { | |
| k = new Transaction(i,s.accept(),Outputs); | |
| k.start(); | |
| i++; | |
| System.out.println("client joined");}//wait for client to connect | |
| } | |
| } | |
| class Transaction extends Thread | |
| { | |
| SynchList outputs; | |
| InputStream b; | |
| OutputStream p; | |
| public Transaction(int i,Socket s, SynchList v) throws Exception | |
| { | |
| outputs=v; | |
| b = s.getInputStream(); | |
| p = s.getOutputStream(); | |
| outputs.add(p); | |
| } | |
| @Override | |
| public void run() | |
| { | |
| int c; | |
| try { | |
| while((c=b.read())!=-1) | |
| { | |
| for (int j=0;j<outputs.size();j++) | |
| { | |
| //if (j!=n) | |
| { | |
| (outputs.get(j)).write(c); | |
| (outputs.get(j)).flush(); | |
| } | |
| } | |
| System.out.print((char)c); | |
| } | |
| System.out.print("left loop"); | |
| } | |
| catch (Exception e) | |
| { | |
| System.out.print(e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment