首页 > 代码库 > ServerSocket服务器
ServerSocket服务器
package cn.hackcoder.action; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.Inet4Address; import java.net.ServerSocket; import java.net.Socket; public class HttpServer { private static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webapp"; private ServerSocket server; private static final String SHUT_DWON = "/shutdown"; private static final int SIZE = 2048; HttpServer(int port, int backlog, String serverName) throws IOException { server = new ServerSocket(port, backlog, Inet4Address.getByName(serverName)); } public void execute() throws IOException { BufferedInputStream bis = null; StringBuffer sb = null; byte[] bytes = new byte[SIZE]; Socket client = null; while (true) { client = server.accept(); OutputStream out = client.getOutputStream(); System.out.println("============= 客户端连接上===========" + client.getInetAddress()); bis = new BufferedInputStream(client.getInputStream()); sb = new StringBuffer(); int ch = bis.read(bytes, 0, SIZE); for (int i = 0; i < ch; i++) { sb.append((char) bytes[i]); } System.out.println("==========请求内容===========\n" + sb); int index1 = sb.indexOf(" "); int index2 = sb.substring(index1 + 1).indexOf(" "); String name = ""; if (index1 < index2) name = sb.substring(index1 + 1, index1 + index2 + 1); System.out.println("----------开始响应------------"); File file = new File(WEB_ROOT, name); if (!file.exists() ||index1 > index2) { PrintStream ps = new PrintStream(out); ps.print("<h1>ERROR</h1>"); bis.close(); ps.close(); continue; } InputStream in = new FileInputStream(file); int len = 0; len = in.read(bytes); while (len != -1) { out.write(bytes, 0, len); len = in.read(bytes); } System.out.println("------------响应结束------------"); in.close(); bis.close(); out.close(); System.out.println("服务器关闭"); } } public static void main(String[] args) { try { new HttpServer(8888, 10, "127.1.1.111").execute(); } catch (IOException e) { e.printStackTrace(); } } public void close() { try { if (server != null && !server.isClosed()) server.close(); } catch (IOException e) { e.printStackTrace(); } } }
ServerSocket服务器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。