简单是挺简单的,主要是作为一个基础性的了解吧
代码如下:
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("" + "" + " 您提交的数据如下:HTTP协议测试服务器,当前时间:" + new java.util.Date() + "
" + " " + " " + " " + "" + sb.toString() + ""); is.close(); out.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("服务器关闭了"); }}