本帖最后由 weimoliang 于 2014-5-14 23:39 编辑
1.浏览器(除360浏览器,这个屌丝一个。)输入 地址 ,如 127.0.0.1:8989
2.服务端Java代码。打印出http请求协议,然后回应客户一个信息!
看代码:
- public class MyServer {
- public static void main(String[] args) {
- try {
- ServerSocket ss = new ServerSocket(8989);
- while(true){
- new Thread(new ConcrrunetServer(ss.accept())).start();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- }
- class ConcrrunetServer implements Runnable{
- private Socket s;
- public ConcrrunetServer(Socket s) {
- this.s = s;
- }
- @Override
- public void run() {
- //读取浏览器头信息
- BufferedInputStream in = null;
- //响应浏览器
- PrintWriter out = null;
- try {
- in = new BufferedInputStream(s.getInputStream());
- out = new PrintWriter(s.getOutputStream());
- byte[] buf = new byte[1024];
-
- int len = 0;
- while((len = in.read(buf)) != -1){ //问题一,循环读取貌似不能定下来,阻塞到这里了
- System.out.println(new String(buf,0,len));
- }
-
- // int len = in.read(buf);
- // System.out.println(new String(buf,0,len));
-
- out.print("<h1>welcom to you !!!</h1>");
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- out.close();//问题2,为什么先关闭输出流浏览器才能得到信息
- try {
- if(in != null)
- in.close();
- //out.close();
- s.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- }
-
- }
-
- }
复制代码 问题:1.循环读取貌似不能停下来,用下面那个注释掉的就没提了。
2.输出流为什么要这输入了之前先关闭!
|
|