java socket定期向浏览器发送页面

时间:2018-06-16 15:30:18

标签: java sockets browser

这只是一项练习。 我想从java服务器套接字向浏览器发送一个计数器。 我编写的代码仅适用于显示“Hello world 0”的第一个计数:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(55555); 
        } catch (IOException e) 
        {
            System.err.println("Could not listen on port: 55555.");
            System.exit(1);
        }

        Socket clientSocket = null; 
        try {
            clientSocket = serverSocket.accept();

            if(clientSocket != null)                
                System.out.println("Connected");

        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out;
        try {
            out = new PrintWriter(clientSocket.getOutputStream());
            for(int i=0;i<100;i++) {
                String s = "<p> Hello world "+i+"</p>";

                out.println("HTTP/1.1 200 OK");
                out.println("Content-Type: text/html");
                out.println("Content-Length: "+s.length());
                out.println("Connection: keep-alive");
                out.println("\r\n");

                out.println(s);
                out.flush();
                System.out.println(s);
                Thread.sleep(1000);
            }

            //out.close();

            //clientSocket.close();
            //serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

可能还是Connection:keep-alive用于更大的文件传输? 感谢

0 个答案:

没有答案