Standalone WebSocket server without JEE/application server

前端 未结 2 2042
清歌不尽
清歌不尽 2021-02-02 18:06

I need to implement a fairly simple WebSocket server in Java SE. All it needs to do is accept connections and store the respective sessions, then send a message to all connected

2条回答
  •  一向
    一向 (楼主)
    2021-02-02 18:35

    Java 11 Server Code:

    package org.treez.server.websocket;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import javax.xml.bind.DatatypeConverter;;
    
    public class WebSocketServer{
    
    
        public static void main(String[] args){
    
            int portNumber = 8000;
    
            ServerSocket server;
            try {
                server = new ServerSocket(portNumber);
            } catch (IOException exception) {
                throw new IllegalStateException("Could not create web server", exception);
            }
    
    
            Socket clientSocket;
            try {
                clientSocket = server.accept(); //waits until a client connects
            } catch (IOException waitException) {
                throw new IllegalStateException("Could not wait for client connection", waitException);
            }
    
            InputStream inputStream;
            try {
                inputStream  = clientSocket.getInputStream();
            } catch (IOException inputStreamException) {
                throw new IllegalStateException("Could not connect to client input stream", inputStreamException);
            }
    
            OutputStream outputStream;
            try {
                outputStream  = clientSocket.getOutputStream();
            } catch (IOException inputStreamException) {
                throw new IllegalStateException("Could not connect to client input stream", inputStreamException);
            }
    
            try {
                doHandShakeToInitializeWebSocketConnection(inputStream, outputStream);
            } catch (UnsupportedEncodingException handShakeException) {
                throw new IllegalStateException("Could not connect to client input stream", handShakeException);
            }
    
    
            try {        
                outputStream.write(encode("Hello from Server!"));
                outputStream.flush();
            } catch (UnsupportedEncodingException e) {          
                e.printStackTrace();
            } catch (IOException e) {       
                e.printStackTrace();
            }   
    
             try {
                    printInputStream(inputStream);
                } catch (IOException printException) {
                    throw new IllegalStateException("Could not connect to client input stream", printException);
                }
    
        }
    
        //Source for encoding and decoding:
        //https://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side
    
    
        private static void printInputStream(InputStream inputStream) throws IOException {
            int len = 0;            
            byte[] b = new byte[1024];
            //rawIn is a Socket.getInputStream();
            while(true){
                len = inputStream.read(b);
                if(len!=-1){
    
                    byte rLength = 0;
                    int rMaskIndex = 2;
                    int rDataStart = 0;
                    //b[0] is always text in my case so no need to check;
                    byte data = b[1];
                    byte op = (byte) 127;
                    rLength = (byte) (data & op);
    
                    if(rLength==(byte)126) rMaskIndex=4;
                    if(rLength==(byte)127) rMaskIndex=10;
    
                    byte[] masks = new byte[4];
    
                    int j=0;
                    int i=0;
                    for(i=rMaskIndex;i<(rMaskIndex+4);i++){
                        masks[j] = b[i];
                        j++;
                    }
    
                    rDataStart = rMaskIndex + 4;
    
                    int messLen = len - rDataStart;
    
                    byte[] message = new byte[messLen];
    
                    for(i=rDataStart, j=0; i= 126 && rawData.length <= 65535){
                frame[1] = (byte) 126;
                int len = rawData.length;
                frame[2] = (byte)((len >> 8 ) & (byte)255);
                frame[3] = (byte)(len & (byte)255); 
                frameCount = 4;
            }else{
                frame[1] = (byte) 127;
                int len = rawData.length;
                frame[2] = (byte)((len >> 56 ) & (byte)255);
                frame[3] = (byte)((len >> 48 ) & (byte)255);
                frame[4] = (byte)((len >> 40 ) & (byte)255);
                frame[5] = (byte)((len >> 32 ) & (byte)255);
                frame[6] = (byte)((len >> 24 ) & (byte)255);
                frame[7] = (byte)((len >> 16 ) & (byte)255);
                frame[8] = (byte)((len >> 8 ) & (byte)255);
                frame[9] = (byte)(len & (byte)255);
                frameCount = 10;
            }
    
            int bLength = frameCount + rawData.length;
    
            byte[] reply = new byte[bLength];
    
            int bLim = 0;
            for(int i=0; i

    pom.xml:

    
      4.0.0
      TreezHttpServer
      TreezHttpServer
      0.0.1-SNAPSHOT
      
        src
        
          
            src
            
              **/*.java
            
          
        
        
          
            maven-compiler-plugin
            3.8.0
            
              11
            
          
            
    
      
    
      
    
        
            javax.xml.bind
            jaxb-api
            2.2.11
        
        
            com.sun.xml.bind
            jaxb-core
            2.2.11
        
        
            com.sun.xml.bind
            jaxb-impl
            2.2.11
        
        
            javax.activation
            activation
            1.1.1
        
    
      
    
    

    JavaScript Client:

    
    
    
    
    
    
    
    
    WebSocket Client
    
     
    
    
    
    
    
    
    
    

提交回复
热议问题