栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

具有Java / Socket的简单Http服务器?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

具有Java / Socket的简单Http服务器?

除了

rn
每个请求标头行之后,您还必须在标头之后发送一个空行。例:

out.write("HTTP/1.0 200 OKrn");// Header...out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMTrn");out.write("rn"); // The content starts afters this empty lineout.write("<TITLE>Hello!</TITLE>");// Content...

我更正了您的代码,使其可以正常工作(但仍然不完美,您应该在单独的线程中处理每个请求,例如使用

java.util.concurrent.ThreadPoolExecutor
):

public static void main(String[] args) throws Exception {    // création de la socket    int port = 1989;    ServerSocket serverSocket = new ServerSocket(port);    System.err.println("Serveur lancé sur le port : " + port);    // repeatedly wait for connections, and process    while (true) {        // on reste bloqué sur l'attente d'une demande client        Socket clientSocket = serverSocket.accept();        System.err.println("Nouveau client connecté");        // on ouvre un flux de converation        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));        // chaque fois qu'une donnée est lue sur le réseau on la renvoi sur        // le flux d'écriture.        // la donnée lue est donc retournée exactement au même client.        String s;        while ((s = in.readLine()) != null) { System.out.println(s); if (s.isEmpty()) {     break; }        }        out.write("HTTP/1.0 200 OKrn");        out.write("Date: Fri, 31 Dec 1999 23:59:59 GMTrn");        out.write("Server: Apache/0.8.4rn");        out.write("Content-Type: text/htmlrn");        out.write("Content-Length: 59rn");        out.write("Expires: Sat, 01 Jan 2000 00:59:59 GMTrn");        out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMTrn");        out.write("rn");        out.write("<TITLE>Exemple</TITLE>");        out.write("<P>Ceci est une page d'exemple.</P>");        // on ferme les flux.        System.err.println("Connexion avec le client terminée");        out.close();        in.close();        clientSocket.close();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486107.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号