Advertisement
zgillis

Voice Echo Server

Jul 23rd, 2012
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. import java.net.*;
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. public class Echo
  6. {
  7.     public static void main(String[] args) throws Exception
  8.     {
  9.         ServerSocket serverSocket = new ServerSocket(3000);
  10.         while(true){Thread echoThread = new Thread(new EchoThread(serverSocket.accept()));
  11.                     echoThread.start();}
  12.     }
  13. }
  14.  
  15. class EchoThread implements Runnable
  16. {
  17.     public static Collection<Socket> sockets = new ArrayList<Socket>();
  18.     Socket connection = null;
  19.     DataInputStream dataIn = null;
  20.     DataOutputStream dataOut = null;
  21.    
  22.     public EchoThread(Socket conn) throws Exception
  23.     {
  24.         connection = conn;
  25.         dataIn = new DataInputStream(connection.getInputStream());
  26.         dataOut = new DataOutputStream(connection.getOutputStream());
  27.         sockets.add(connection);
  28.     }
  29.    
  30.     public void run()
  31.     {
  32.         int bytesRead = 0;
  33.         byte[] inBytes = new byte[1];
  34.         while(bytesRead != -1)
  35.         {
  36.             try{bytesRead = dataIn.read(inBytes, 0, inBytes.length);}catch (IOException e){}
  37.             if(bytesRead >= 0)
  38.             {
  39.                 sendToAll(inBytes, bytesRead);
  40.             }
  41.         }
  42.         sockets.remove(connection);
  43.     }
  44.    
  45.     public static void sendToAll(byte[] byteArray, int q)
  46.     {
  47.         Iterator<Socket> sockIt = sockets.iterator();
  48.         while(sockIt.hasNext())
  49.         {
  50.             Socket temp = sockIt.next();
  51.             DataOutputStream tempOut = null;
  52.             try
  53.             {
  54.                 tempOut = new DataOutputStream(temp.getOutputStream());
  55.             } catch (IOException e1)
  56.             {
  57.                 // TODO Auto-generated catch block
  58.                 e1.printStackTrace();
  59.             }
  60.             try{tempOut.write(byteArray, 0, q);}catch (IOException e){}
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement