服務端程式碼

server.SimpleSocketServer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package server;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
 
public class SimpleSocketServer {
     
    public void doAccept(Socket socket) throws Exception{
        InputStream is = socket.getInputStream();
         
        System.out.println("receive below information from client ... ");
        byte[] bytes = new byte[1024];
        int length = -1;
        while((length=is.read(bytes, 01024))>0){
            int breakLineCount = 0;
            for(int i=0;i<length;i++){
                char c = (char) bytes[i];
                System.out.print(c);
                if(`
`
==c){
                    breakLineCount++;
                }
            }
            if(breakLineCount>1){
                break;
            }
        }
         
        String response = getSimpleRespose();
        OutputStream os = socket.getOutputStream();
        os.write(response.getBytes());
         
        os.flush();
         
        socket.close();
         
    }
     
    private String getSimpleRespose() throws Exception{
        InputStream is = this.getClass().getResourceAsStream("simple_response");
         
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
         
        String line = null;
         
        StringBuilder response = new StringBuilder();
         
        while((line=br.readLine())!=null){
            response.append(line).append("
"
);
        }
         
        String text = getRandomRes();
         
        response.append("Content-Length:"+text.length()).append("

"

)
                .append(text);
         
        return response.toString();
    }
     
    private String getRandomRes(){
        Random random = new Random();
        if(random.nextInt(10)%2==0){
            return getDataWithEventRes();
        }else{
            return getDataRes();
        }
    }
     
    private String getDataRes(){
        Random random = new Random();
        int randomValue = random.nextInt(1000);
        String text = "data:the random value is : "+randomValue;
        text+="

"

;
        return text;
    }
     
    private String getDataWithEventRes(){
        Random random = new Random();
        int randomValue = random.nextInt(1000);
        String text = "data:the random value is : "+randomValue+"
"
;
        text+="event:myevent";
        text+="

"

;
        return text;
    }
     
    public void start() throws Exception{
        ServerSocket serverSocket = new ServerSocket(8888);
         
        while(true){
            Socket socket = serverSocket.accept();
            doAccept(socket);
        }
         
    }
    public static void main(String[] args) throws Exception{
         
        new SimpleSocketServer().start();
    }
}

server/simple_response

1
2
HTTP/1.1 200 OK
Content-Type: text/event-stream

客戶端html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<body>
    <h1>獲得伺服器更新</h1>
    <div id="result"></div>
 
 <script>
    if(typeof(EventSource)!=="undefined"){
        var source=new EventSource("http://localhost:8888/");
        source.onopen = function(){
            console.log("connection opened ... ");
        };
 
        source.onmessage=function(event){
            document.getElementById("result").innerHTML+=event.data + "<br />";
        };
 
        source.addEventListener("myevent", function(event) {
            console.log("event:"+event.type);
            console.log(event.data);
        });
 
        source.onerror = function(){
            console.log("connection close ... ");
        };
 
    }else{
      document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
    }
</script>
 
</body>
</html>