Advertisement
Mihael

Java websocket server draft

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