`

java建立socket,返回浏览器的请求

阅读更多
package com.jdk.api.test;

import java.io.DataInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;



public class WebServer{

public static void main(String args[]) throws Exception

{

 
     int i=1,PORT=8080;
  ServerSocket server=null;
   Socket client=null;
   server=new ServerSocket(PORT);
System.out.println("Web Server is listening on port"+String.valueOf(server.getLocalPort()));
while(true){
client=server.accept();
System.out.println("有一个浏览器访问我了!!");
new Connection(client).start();
}
  }


}
class Connection  extends Thread{

Socket client;
public Connection(Socket cl){

client=cl;
}
public void run(){
try{


PrintStream outstream=new PrintStream(client.getOutputStream());

DataInputStream instream = new DataInputStream(client.getInputStream());
StringBuilder sb = new StringBuilder();
String inline = null;
/**
* instream.readLine() 是阻塞的,
*     应该使用instream.available()判断是否有可用的流可以读取
*
*/
while((inline  =instream.readLine())!= null && instream.available()>0 ){
System.out.println("------------------------");
sb.append(inline);

}

      System.out.println("receive:"+sb);
        String ss = sb.toString();
System.out.println("ss:"+ss);
      byte buf[]=ss.getBytes();
    System.out.println("lenth:"+buf.length);

      outstream.write(buf,0, buf.length-1);

      outstream.flush();

      outstream.close();
      client.close();
}catch(Exception ex){
ex.printStackTrace();
}
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics