package 网络编程; 
import java.net.*; 
import java.io.*; 
public class 浏览器客户端 { 
        public static void main(String[] args) throws Exception{ 
                ServerSocket ss=new ServerSocket(10010); 
                Socket s=ss.accept(); 
                System.out.println(s.getInetAddress().getHostAddress()); 
                PrintWriter pw=new PrintWriter(s.getOutputStream(),true); 
                pw.write("欢迎光临"); 
                BufferedReader bufin=new BufferedReader(new InputStreamReader(s.getInputStream())); 
                byte[] buf=new byte[1024]; 
                String line=null; 
                while((line=bufin.readLine())!=null){ 
                        System.out.println(line); 
                } 
                bufin.close(); 
                s.close(); 
                ss.close(); 
        } 
} 
 
 
奇怪的是这个服务端可以接收到客户端传来的信息。但是 另外那一段收不到“欢迎光临”。同样的代码,毕老师用浏览器就可以接收。 
 
这是服务端 
package 网络编程; 
import java.io.*; 
import java.net.*; 
public class 测试 { 
        public static void main(String[] args){ 
                String urlPath="http://127.0.0.1:10010"; 
                try{ 
                URL url=new URL(urlPath); 
                URLConnection conn=url.openConnection(); 
                InputStream in=conn.getInputStream(); 
                byte[] buf=new byte[1024]; 
                int len=0; 
                while((len=in.read(buf))!=-1){ 
                        System.out.println("2222222");  //该用来测试,结果也不输出,就没有输入流进来 
                        System.out.println(new String(buf,0,len)); 
                } 
                }catch(Exception ex){ 
                        System.out.println("URL不正确"); 
                } 
         
        } 
} 
 
最终服务端打印: 
127.0.0.1 
GET / HTTP/1.1 
User-Agent: Java/1.7.0_15 
Host: 127.0.0.1:10010 
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 
Connection: keep-alive 
客户端什么都没有。 |