简单的Socket实现web功能
简单是挺简单的,主要是作为一个基础性的了解吧
代码如下:
public class SocketServer { public static void main(String[] args) { Socket socket=null; try { ServerSocket serverSocket=new ServerSocket(9001, 3); System.out.println("服务器启动等待链接"); while(true){ socket=serverSocket.accept(); System.out.println("链接已经建立:端口号为:"+socket.getPort()); new WebThread(socket).start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class WebThread extends Thread{ private Socket socket; public WebThread(Socket socket) { super(); this.socket = socket; } public void run(){ try { PrintStream out=new PrintStream(socket.getOutputStream()); InputStreamReader is=new InputStreamReader(socket.getInputStream()); BufferedReader br=new BufferedReader(is); StringBuilder sb=new StringBuilder(); String s=""; while(!(s=br.readLine()).equals("")){ sb.append(s); sb.append("\n"); System.out.println("客户端发来信息:"+s); } socket.shutdownInput(); out.println("HTTP/1.1 200 OK"); out.println("Content-Type:text/html;charset:GBK"); out.println(); // 2、输出主页信息 out .println("<HTML><BODY>" + "<center>" + "<H1>HTTP协议测试服务器,当前时间:" + new java.util.Date() + "</h1>" + "<form method='get'>username:<input type='text' name='username'/>password:<input type='text' name='password'/><input type='submit' value='GET测试'/></form><br/>" + "<form method='post'>username:<input type='text' name='username'/>password:<input type='text' name='password'/><input type='submit' value='POST测试'/></form><br/>" + "<form method='post' enctype='multipart/form-data'>phototitle:<input type='text' name='phototitle'/>photo:<input type='file' name='photo'/><input type='submit' value='Upload测试'/></form>" + "</center>您提交的数据如下:<pre>" + sb.toString() + "</pre></BODY></HTML>"); is.close(); out.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("服务器关闭了"); } }