Advertisement
Mihael

Java websocket server draft

Mar 7th, 2012
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.81 KB | None | 0 0
  1. import java.io.*;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.net.*;
  4. import java.security.MessageDigest;
  5. import java.util.Properties;
  6.  
  7. public class BrogamingServer extends Thread{
  8.  
  9.     Socket s;
  10.     int num;
  11.    
  12.     public BrogamingServer(int num, Socket s) {
  13.         // copy data
  14.         this.num = num;
  15.         this.s = s;
  16.        
  17.         // and run new stream (look function run())
  18.         setDaemon(true);
  19.         setPriority(NORM_PRIORITY);
  20.         start();
  21.     }
  22.    
  23.     public static void main(String args[]) {
  24.         try {
  25.             int i = 0; // счетчик подключений
  26.        
  27.             // create socket on 3128 port
  28.             ServerSocket server = new ServerSocket(3128);//, 0, InetAddress.getByName("192.168.1.9"));
  29.        
  30.             System.out.println("server is started");
  31.        
  32.             // listening port
  33.             while(true) {
  34.                 new BrogamingServer(i, server.accept());
  35.                 i++;
  36.             }
  37.         }catch(Exception e){System.out.println("init error: " + e);}
  38.     }
  39.    
  40.    
  41.    
  42.     public void run() {
  43.         try {
  44.             Thread t = new Thread(new Runnable() {
  45.                 @Override
  46.                 public void run() {
  47.                     System.out.println("client connected");
  48.                     RecieveDataFromClient();
  49.                 }
  50.             });
  51.             t.setDaemon(true);
  52.             t.start();
  53.         }catch(Exception e){System.out.println("init error: " + e);}
  54.     }
  55.    
  56.     private void RecieveDataFromClient() {
  57.         try {
  58.             InputStream is = s.getInputStream();
  59.             OutputStream os = s.getOutputStream();
  60.            
  61.             startConnection(is, os);
  62.            
  63.             while(s.isConnected())
  64.             {
  65.                
  66.                
  67.                 byte buf[] = new byte[64*1024];
  68.                 int r = is.read(buf);
  69.                
  70.                 if (buf.length == 0 || r == 0)
  71.                 {
  72.                     os.write(new String("Buffer is empty").getBytes());
  73.                     continue;
  74.                 }
  75.                
  76.                 // create String with received data from client
  77.                 String data = new String(buf, 0, r); //"UTF-8");
  78.                
  79.                 if (data == null || data.isEmpty())
  80.                 {
  81.                     os.write(new String("Recieved data is empty").getBytes());
  82.                     continue;
  83.                 }
  84.                 System.out.println("Recieved Data: " + data);
  85.                 os.write(new String("pong").getBytes());
  86.                 os.flush();
  87.             }
  88.         }
  89.         catch(Exception e) {System.out.println("RecieveDataFromClient: " + e);}
  90.     }
  91.    
  92.     private void startConnection(InputStream is, OutputStream os) {
  93.         try {
  94.             String ss;
  95.             readLine(is); // first line, ignore it for now
  96.             Properties props = new Properties();
  97.             while((ss=readLine(is))!=null && !ss.equals(""))
  98.             {
  99.                 String[] q = ss.split(": ");
  100.                 props.put(q[0], q[1]);
  101.             }
  102.             String key = (String) props.get("Sec-WebSocket-Key");
  103.             String r = key + "" + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // append "magic" key to it
  104.            
  105.             MessageDigest md = MessageDigest.getInstance("SHA-1");
  106.             md.update(r.getBytes("iso-8859-1"), 0, r.length());
  107.             byte[] sha1hash = md.digest();
  108.  
  109.             String returnBase = base64(sha1hash);
  110.            
  111.             String ret = "HTTP/1.1 101 Switching Protocols\r\n";
  112.                 ret+="Upgrade: websocket\r\n";
  113.                 ret+="Connection: Upgrade\r\n";
  114.                 ret+="Sec-WebSocket-Accept: "+returnBase+"\r\n";
  115.                 ret+="\r\n";
  116.             os.write(ret.getBytes());
  117.             os.flush();
  118.         }catch(Exception e){System.out.println("start connection error: " + e);}
  119.        
  120.     }
  121.  
  122.     private String base64(byte[] input) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException
  123.     {
  124.         Class<?> c = Class.forName("sun.misc.BASE64Encoder");
  125.         java.lang.reflect.Method m = c.getMethod("encode", new Class<?>[]{byte[].class});
  126.         String s = (String) m.invoke(c.newInstance(), input);
  127.         return s;
  128.     }
  129.    
  130.     private String readLine(InputStream in) {
  131.         try {
  132.             String line = "";
  133.             int pread;
  134.             int read = 0;
  135.             while(true)
  136.             {
  137.                 pread = read;
  138.                 read = in.read();
  139.                 if(read!=13&&read!=10)
  140.                     line += (char) read;
  141.                 if(pread==13&&read==10) break;
  142.             }
  143.             return line;
  144.         }catch(IOException ex){}
  145.         return null;
  146.     }
  147.  
  148. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement