Java基础(24)网络编程
2015-04-08 15:44
826 查看
十一:网络编程 TCP-复制文件
实现:客户端发给服务端,然后在服务端保存起来import java.io.*; import java.net.*; //客户端 class InetTextDemo { public static void main(String[] args)throws Exception { Socket s = new Socket("192.168.126.1",10006); //源 BufferedReader bufr = new BufferedReader (new FileReader("E:\\hebing\\net.txt")); //目的 BufferedWriter bufout = new BufferedWriter (new OutputStreamWriter(s.getOutputStream())); //PrintWriter out = new PrintWriter(s.getOutputStream(), true);//这个较为简单用这个 //********************************代码1*********************************** //代码1和代码2效果一样 //接受服务端 欢迎光临的信息 // InputStream in = s.getInputStream(); // byte[] buf =new byte[1024]; // int len = in.read(buf); // System.out.println(new String(buf, 0 , len)); //BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); //String str = bufin.readLine(); //读socket流,因为服务端卡在while那,所以不会发数据给客户端,所以一直卡在这,两边都卡着 //System.out.println(str); //********************************代码1************************************ String line = null; while((line = bufr.readLine()) != null) { bufout.write(line); bufout.newLine(); bufout.flush(); //out.println(line); } s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1 //********************************代码2*********************************** ////代码1和代码2效果一样 //接受服务端 欢迎光临的信息 //InputStream in = s.getInputStream(); //byte[] buf =new byte[1024]; //int len = in.read(buf); //System.out.println(new String(buf, 0 , len)); BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = bufin.readLine(); //读socket流,因为服务端卡在while那,所以不会发数据给客户端,所以一直卡在这,两边都卡着 System.out.println(str); //********************************代码2************************************ bufr.close(); s.close(); } }
//服务端
import java.io.*; import java.net.*; //服务端 class InetRece { public static void main(String[] args)throws Exception { ServerSocket ss = new ServerSocket(10006); //获取对象 Socket s = ss.accept(); //打印连接上的客户端 String ip =s.getInetAddress().getHostAddress(); System.out.println(ip+"...connected"); //源 BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); //目的 BufferedWriter bufw = new BufferedWriter(new FileWriter("E:\\hebing\\servet.txt")); //PrintWriter out = new PrintWriter(new FileWriter("E:\\server.txt"),true); String line = null; //客户端把要复制的文件写到输出流中,没有给出结束标志,这里就一直在读读到文件末尾,也没读到换行符,所以又卡这里!!!!!! //上面的写到流中虽然写完了,但是往下走,又走到读取服务端”上传成功”的readLine卡在那了(按实际分析,放的位置不一定一样) //读取的文件中数据没有给结束符。 while((line = bufin.readLine()) != null) { bufw.write(line); bufw.newLine(); bufw.flush(); //out.println(line); } //写 欢迎使用 BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bufout.write("上传成功"); bufout.flush(); //如果这里不写数据根本就没写进socket输出流中,导致对面一直在等 //PrintWriter pw = new PrintWriter(s.getOutputStream(), true); //这种较为简便,以后是用这个 //pw.println("上传成功"); //out.close(); bufw.close(); s.close(); ss.close(); } }
十二.网络编程-TCP复制图片
原理跟上传文件一样客户端 1.服务端点。 2.读取客户端已有的图片数据。 3.通过socket输出流将数据发给服务端。 4.读取服务端反馈信息 5.关闭。 import java.io.*; import java.net.*; class IoTextDemo { public static void main(String[] args)throws Exception { //1.建立socket端点 Socket s = new Socket("192.168.126.1",10006); //源 FileInputStream fis = new FileInputStream("C:\\daxiong.jpeg"); //目的 OutputStream out = s.getOutputStream(); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf)) != -1) { out.write(buf,0,len); } //告诉服务端数据已写完,否则一直卡在read那里 s.shutdownOutput(); InputStream in = s.getInputStream(); byte[] bufin = new byte[1024]; int num = in.read(bufin); System.out.println(new String(bufin , 0 , num)); // BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); // String str = bufin.readLine(); //读socket流,因为服务端卡在while那,所以不会发数据给客户端,所以一直卡在这,两边都卡着 // System.out.println(str); fis.close(); s.close(); } }
import java.io.*; import java.net.*; //服务端 class InetRece { public static void main(String[] args)throws Exception { //1。建立ServerSocket服务 ServerSocket ss = new ServerSocket(10006); //2.获取对象 //获取对象 Socket s = ss.accept(); String ip =s.getInetAddress().getHostAddress(); System.out.println(ip+"...connected"); InputStream in = s.getInputStream(); FileOutputStream fos = new FileOutputStream("E:\\hebing\\server7.jpeg"); //打印连接上的客户端 byte[] buf = new byte[1024]; int len = 0; while((len = in.read(buf)) != -1)//客户端在流中没写介乎标记 { fos.write(buf,0,len); } //发送给客户端 上传成功 OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); //写 欢迎使用 //BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); //bufout.write("上传成功"); //bufout.flush(); //如果这里不写数据根本就没写进socket输出流中,导致对面一直在等 fos.close(); s.close(); ss.close(); } }
十三.并发上传图片
//客户端并发上传图片import java.io.*; import java.net.*; class InetTextDemo { //编译的时候 java PicClient C:\1.jpg 相当于传了一个参数(args[0]) public static void main(String[] args)throws Exception { if(args.length >1)//代表传的参数是不是一个 { System.out.println("上传的文件数大于1"); return ; } File file = new File(args[0]); if(!(file.exists()&&file.isFile())) { System.out.println("不存在或者不是文件类型"); return; } if(!file.getName().endsWith(".jpeg")) { System.out.println("格式错误,请重新选择"); return; } if(file.length()>1024*1024*5)//5M { System.out.println("文件过大"); } Socket s = new Socket("192.168.126.1",10008); //源 FileInputStream fis = new FileInputStream(file); //目的 OutputStream out = s.getOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = fis.read(buf)) != -1) { out.write(buf , 0 ,len); } s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1 BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = bufin.readLine(); //读socket流,因为服务端卡在while那,所以不会发数据给客户端,所以一直卡在这,两边都卡着 System.out.println(str); fis.close(); s.close(); } }
服务端
这个服务端有个局限性,当A客户端连接上以后。被服务端获取到。服务端执行具体流程。
这时B客户端连接,只有等待。
因为服务端还没有处理完A客户端的请求,还有循环回来执行下次accept方法。所以暂时获取不到B客户端对象。
那么为了可以让多个客户端同时并发访问服务端。
那么服务端最好就是将每个客户端封装到一个单独的线程中,这样,就可以同时处理多个客户端请求。
import java.io.*; import java.net.*; //服务端 class InetReceive implements Runnable { private Socket s; InetReceive(Socket s) { this.s = s; } public void run() { //打印连接上的客户端 int count = 1; String ip =s.getInetAddress().getHostAddress(); System.out.println(ip+"...connected"); try { //源 //BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); InputStream in = s.getInputStream(); File file = new File("E:\\hebing\\"+ip+"("+count+").jpeg"); //有点生疏了 while(file.exists()) //避免覆盖之前的文件 { file = new File("E:\\hebing\\"+ip+"("+(count++)+").jpeg"); } //目的 FileOutputStream fos = new FileOutputStream(file); //BufferedWriter bufw = new BufferedWriter(new FileWriter("E:\\hebing\\servet3.txt")); //PrintWriter out = new PrintWriter(new FileWriter("E:\\server.txt"),true); //String line = null; int len = 0; byte[] buf = new byte[1024]; //客户端把要复制的文件写到输出流中,没有给出结束标志,这里就一直在读读到文件末尾,也没读到换行符,所以又卡这里!!!!!! //上面的写到流中虽然写完了,但是往下走,又走到读取服务端”上传成功”的readLine卡在那了(按实际分析,放的位置不一定一样) //读取的文件中数据没有给结束符。 while((len = in.read(buf)) != -1) { //bufw.write(line); //bufw.newLine(); //bufw.flush(); fos.write(buf , 0 , len); //out.println(line); } //写 欢迎使用 BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bufout.write("上传成功"); bufout.flush(); //如果这里不写数据根本就没写进socket输出流中,导致对面一直在等 fos.close(); s.close(); //ss.close(); } catch (Exception e) { throw new RuntimeException("上传失败"); } //out.close(); } } class InetRece { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10008); while(true) { Socket s = ss.accept();//获取客户端,但是目前只能在一个客户端关闭才能接受其他客户端, //这个方法是阻塞式的(!!!!!!),等待客户端连接,所以不能放上面的里面 //如果这么写就定了一个线程,不能这么写 //Thread t1 = new Thread(new InetReceive(s)); new Thread(new InetReceive(s)).start();//如果来了一个客户端,就开了一个客户端,主线程再跑,于是就又开了线程 } } }
十四.网络编程:客户端并发登陆
网络编程:客户端并发登陆客户端通过键盘录入用户名。
服务端对这个用户名进行校验。
如果该用户存在,在服务端显示XXX,已登录。
并在客户端显示XXX,欢迎光临。
如果该用户存在,在服务端显示XXX,尝试登陆。
并在客户端显示XXX,该用户不存在。
最多登陆三次。
import java.io.*; import java.net.*; //客户端 class InetTextDemo { public static void main(String[] args) throws Exception { Socket s = new Socket("192.168.126.1",10008); //源 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); //目的 //PrintWriter//如果是PrintWriter out.write("登陆失败") PrintStream.write("登陆失败".getBytes)!!!就像InputStream reader 没什么差别 PrintStream out = new PrintStream(s.getOutputStream(),true); //可以自动刷新,不用再些刷新 //PrintWriter out = new PrintWriter(s.getOutputStream(),true); //接受服务端的反馈信息 BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); //读三次,如果三次都不成功就停止登陆 for(int x = 0 ; x<3;x++) { System.out.println("dsr"); String line = bufr.readLine();//输入一次读取一次 System.out.println("dsr over"); if(line == null) //确保按ctrl+c时停止输入,按ctrl+c时就给流-1,readLine底层的read读到-1,就返回null { break; } //out.println(line);//写到socket输出流中发给服务端 System.out.println("xsj"); out.println(line); //out.println();//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!注意这里要写个换行符,不然服务端的ReadLine()一直读不到换行符,在那堵着 System.out.println("xsj over"); //判断服务端反馈回来的信息,如果反馈欢迎使用之类的就不用登录了 System.out.println("dfksj"); String info = bufin.readLine();//读取服务端反馈回来的信息 System.out.println("dfksj over"); System.out.println("info:"+info); if(info.contains("欢迎")) //读到有 欢迎 就停止登陆 { break; } else //没读到就说用户不存在 { //System.out.println("用户不存在,请重新登陆"); } } s.close(); bufr.close(); } }
//服务端
import java.io.*; import java.net.*; class InetReceive implements Runnable { private Socket s; InetReceive(Socket s) { this.s = s; } public void run() { String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"....connected"); try { for(int x = 0 ;x<3;x++) { //源 BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); //如果放外面就只创建一次,这边是输三次,每次都不一样 //目的(写欢迎使用之类的) PrintStream out = new PrintStream(s.getOutputStream(),true) ; //如果放外面就只创建一次,这边是输三次,每次都不一样 //PrintWriter out = new PrintWriter(s.getOutputStream(),true) ; //读取本地数据(记录已经注册用户的文件) BufferedReader bufr = new BufferedReader(new FileReader ("E:\\hebing\\login_record.txt")); //如果放外面就只创建一次,这边是输三次,每次都不一样 System.out.println("dsj"); String name = bufin.readLine();//读取客户端写过来的数据 System.out.println("dsj over"); if(name == null) { break; } String line = null; boolean succ_flag = false; while((line = bufr.readLine()) != null) { if(name.equals(line)) { succ_flag = true; break; } } //这时候有可能是成功调处循环,也有可能读完本地本件 if(succ_flag == true)//登陆成功 { System.out.println("登陆成功"); out.println("欢迎使用"); // out.println(); //out.println(name+"欢迎使用"); } else //登陆不成功 { System.out.println("尝试登录"); out.println("登陆失败");//打印进流里PrintStream out = new PrintStream(s.getOutputStream(),true),相当 写 write()+println(空参数) //如果是PrintWriter out.write("登陆失败") PrintStream.write("登陆失败".getBytes)!!! //out.println();//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!注意这里要写个换行符,不然客户端的ReadLine()一直读不到换行符,在那堵着 //out.println(name+"登陆失败"); } } s.close(); //bufr.close();//为什么不写???? } catch (Exception e) { throw new RuntimeException("服务器错误"); } } } class InetRece { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10008); while(true) { Socket s = ss.accept(); new Thread(new InetReceive(s)).start(); } } }
十五.网络编程-自定义服务端
//自定义服务端import java.io.*;
import java.net.*;
class InetTextDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss = new ServerSocket(11000);
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
PrintWriter out = new PrintWriter(s.getOutputStream() , true);
out.println("<font color = 'red' size = '7'>客户端你好</font>"); //设置字体大小及颜色
s.close();
ss.close();
}
}
//在浏览器中输入http://192.168.126.1:11000
十六.网络编程:浏览器客户端,tomcat服务端
网络编程:浏览器客户端,tomcat服务端1.
客户端:浏览器(telnet)
服务端:自定义。
2.
//打开浏览器通过tomcat服务器访问自定义的网页
客户端:浏览器。
服务端:tomcat服务器。//封装了serverSocket
http://192.168.126.1:8080/ 输入这个 就可以访问tomcat
D:\tomcat\webapps\myweb
在我这个路径下写一个demo.html内容如下
<html>
<body>
<h1>这是我的主页</h1>
<font size =5 color = read>欢迎光临</font>
<div>
啊实打实大师的</br>
啊实打实大师的</br>
啊实打实大师的</br>
</div>
</body>
</html>
然后在浏览器中http://192.168.126.1:8080/myweb/demo.html就可以打印出
//这是我的主页
//欢迎光临
//啊实打实大师的
//啊实打实大师的
//啊实打实大师的
十七.网络编程-自定义浏览器-Tomcat服务端
1.客户端:浏览器(telnet)
服务端:自定义。
2.
//打开浏览器通过tomcat服务器访问自定义的网页
客户端:浏览器。
服务端:tomcat服务器。
3.
客户端:自定义。
服务端:Tomcat服务器。
思考的问题,到底浏览器给服务器发了什么,才能请求到myweb的资源:
import java.io.*; import java.net.*; class InetTextDemo { */ //这是浏览器给服务端发的数据 //783//192.168.126.1 //784//GET / HTTP/1.1 //785//Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gi //786//f, image/pjpeg, application/x-ms-xbap, application/msword, application/vnd.ms-ex //787//cel, application/vnd.ms-powerpoint, */* //788//Accept-Language: zh-CN //789//User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4. //790//0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Cent //791//er PC 6.0; .NET4.0E; .NET4.0C) //792//Accept-Encoding: gzip, deflate //793//Host: 192.168.126.1:11000 //794//Connection: Keep-Alive //794以上是数据头 //795以下是数据体,(这里没有) //两个之间有一行空格,这个是协议规定的 //784 get是一种请求方式 //http://192.168.1.254:11000/myweb/demo.html //http是协议(应用层),tcp是传输层协议 //192.168.126.1:主机名 //11000 端口号 //myweb资源路径 //demo.html 资源 //HTTP/1.1 http的协议版本 //785-787 能接收的数据类型 //788 支持的语言 //792 支持的封装型号,服务器发给客户端的数据是压缩过的 //把给客户端的数据先压缩,然后客户端在解压 //793 要访问的主机和端口好(一个地址可以对应多个主机) //获取浏览器发过来的数据的代码 // public static void main(String[] args)throws Exception // { // ServerSocket ss = new ServerSocket(11000); // Socket s = ss.accept(); // System.out.println(s.getInetAddress().getHostAddress()); // InputStream in = s.getInputStream(); // byte[] buf = new byte[1024]; // int len = in.read(buf); // System.out.println(new String(buf,0,len)); // PrintWriter out = new PrintWriter(s.getOutputStream(),true); // out.println("<font color = 'blue' size = '7'> 客户端你好2</font> "); // s.close(); // ss.close(); // } //模拟浏览器发同样的数据给Tomcat //200,是响应状态码,代表成功。得出的结果跟浏览器一样,如下图 // public static void main(String[] args) throws Exception // { // Socket s = new Socket("192.168.126.1",8080); //我们没有输入的地方只能写死,浏览器有输入的地方 // PrintWriter out = new PrintWriter(s.getOutputStream() , true); //按照http的协议格式 // out.println("GET /myweb/demo.html HTTP/1.1"); //注意不要写多余的空格,否则不符合格式不会接受 // out.println("Accept: */*"); // out.println("Accept-Language: zh-cn"); // out.println("Host: 192.168.126.1:11000"); //out.println("Connection:Keep-Alive"); //程序会一直停着,知道超时 // out.println("Connection:closed") ;//运行完就关闭 // out.println();//消息体跟数据体要空一行,这里保险就空两行 // out.println(); //按照http的协议格式 // BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream())); // String line = null; // while((line = bufr.readLine()) != null) // { // System.out.println(line); // } // s.close(); // } //}
十八.自定义图形界面浏览器
//这里没有研究。。。。只是照着写了代码(也不知道代码有没有用)import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class MyIEByGUI { private Fram f; private TextField tf; private Button but; private TextArea ta; private Dialog d; private Label lab; private Button 0kBut; MyIEByGUI() { init(); } public void init() { f = new Frame("my window"); f.setBounds(300,100,600,500); f.setLayout(new FlowLayout()); tf = new TextField(60); but = new Button("转到"); ta = new TextArea(25,70); d= new Dialog(f,"提示信息-self" , true); d.setBounds(400 , 200 ,240 ,150); d.setLayout(new FlowLayout()); lab = new Label(); okBut= new Button("确定"); d.add(lab); d.add(okBut); d.add(tf); f.add(but); f.add(ta); myEvent(); f.setVisible(true); } public void myEvent() { okBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }); d.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { d.setVisible(false); } }); tf.addKeyListener(new KeyAdapter() { public void keypressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { try { showDir(); } catch(Exception ex) { } } } }); but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { showDir(); } catch(Exception ex) { } } }); f.adWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } private void showDir() throws Exception { ta.setText(""); String ur1 = tf.getText(); //http://192.168.1.254:8080/myweb/demo.html int index1 = ur1.indexof("//")+2; int index2 = ur1.indexof("/",index1); String str = ur1.substring(index1 , index2); String[] arr = str.split(":"); //用冒号分割 String host = arr[0]; int port = Integer.parseInt(arr[1]); String path = ur1.substring(index2); //ta.setText(str+”....”+path); Socket s = new Socket(host,port); //我们没有输入的地方只能写死,浏览器有输入的地方 PrintWriter out = new PrintWriter(s.getOutputStream() , true); //按照http的协议格式 out.println("GET "+path+" HTTP/1.1"); out.println("Accept : */*"); out.println("Accept-Language: zh-cn"); out.println("Host: 192.168.1.254:11000"); //out.println("Connection:Keep-Alive"); //程序会一直停着,知道超时 out.println("Connection:closed") ;//运行完就关闭 out.println(); out.println(); //按照http的协议格式 BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line = bufr.readLine()) != null) { //System.out.println(line); ta.append(line+”\r\n”); } s.close(); String dirpath = tf.getText(); File dir = new File(dirPath); if(dir.exists()&&dir.idDirectory()) { ta.setText(“”); String[] names = dir.list(); for(String name :names) { ta.append(name+”\r\n”); } else { String info = “您输入的的信息:”+dirPath+”是错误的。请重输”; lab.setText(info); d.setVisible(true); } } public static void main(String[] args) { new MyIEByGUI(); } } //}
十九.网络编程URL-URLconnection
类URL 代表一个统一资源定位符,他是指向互联网“资源”的指针,资源可以使简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询URI跟URL区别是前者范围更大(两者都代表唯一定位符)
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; class MyIEByGUI { private Fram f; private TextField tf; private Button but; private TextArea ta; private Dialog d; private Label lab; private Button 0kBut; MyIEByGUI() { init(); } public void init() { f = new Frame("my window"); f.setBounds(300,100,600,500); f.setLayout(new FlowLayout()); tf = new TextField(60); but = new Button("转到"); ta = new TextArea(25,70); d= new Dialog(f,"提示信息-self" , true); d.setBounds(400 , 200 ,240 ,150); d.setLayout(new FlowLayout()); lab = new Label(); okBut= new Button("确定"); d.add(lab); d.add(okBut); d.add(tf); f.add(but); f.add(ta); myEvent(); f.setVisible(true); } public void myEvent() { okBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }); d.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { d.setVisible(false); } }); tf.addKeyListener(new KeyAdapter() { public void keypressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { try { showDir(); } catch(Exception ex) { } } } }); but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { showDir(); } catch(Exception ex) { } } }); f.adWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } private void showDir() throws Exception {
ta.setText(“”); //简化版(右边(因为蓝色)) 跟下面的浏览器有点区别(左边(因为应用层解析)) //之前在传输层收到数据全部展示出来,没有拆包 //现在传输层传到应用层,应用层的http协议把他能识别的数据解开,把正文显示出来 //从键盘输入的到连接 String ur1Path= tf.getText(); //http://192.168.1.254:8080/myweb/demo.html //解析服务器发过来的http信息,取出数据体 URL url = new URL (urlPath); URLConnection conn = url.openConnection(); //解析服务器发过来的http信息,取出数据体 //System.out.println(conn); InputStream in = conn.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); ta.setText(new String(buf,0,len)); } //**************************************复杂了,把它简化*************************************** // String ur1 = tf.getText(); //http://192.168.1.254:8080/myweb/demo.html // int index1 = ur1.indexof(“//”)+2; // int index2 = ur1.indexof(“/”,index1); // String str = ur1.substring(index1 , index2); // String[] arr = str.split(“:”); //用冒号分割 // String host = arr[0]; // int port = Integer.parseInt(arr[1]); // String path = ur1.substring(index2); //ta.setText(str+”....”+path); // Socket s = new Socket(host,port); //我们没有输入的地方只能写死,浏览器有输入的地方 // PrintWriter out = new PrintWriter(s.getOutputStream() , true); // //按照http的协议格式 //URLconnection会发出去不用自己写 // out.println(“GET “+path+” HTTP/1.1”); // out.println(“Accept : */*”); // out.println(“Accept-Language: zh-cn”); // out.println(“Host: 192.168.1.254:11000”); // //out.println(“Connection:Keep-Alive”); //程序会一直停着,知道超时 // out.println(“Connection:closed”) ;//运行完就关闭 // out.println(“”); // out.println(“”); //按照http的协议格式 // // BufferedReader bufr = // new BufferedReader(new InputStreamReader(s.getInputStream())); // String line = null; // while((line = bufr.readLine()) != null) // { // //System.out.println(line); // ta.append(line+”\r\n”); // } // s.close(); //******************************************************************** } public static void main(String[] args) { new MyIEByGUI(); } } }
//但是浏览器是不会打印数据头的
//代码1 import java.net.*; class URLDemo { public static void main (String[] args) throws MalformedURLException { //如果绿色的端口号不写那么 getport() = -1 URL url = new URL("http://192.168.1.254:8080/myweb/demo.html?name=haha&age=30"); System.out.println(“getProtovol():”+url.getProtovol()); System.out.println(“getHost():”+url.getHost()); System.out.println(“getPort():”+url.getPort()); System.out.println(“getPath():”+url.getPath()); System.out.println(“getFile():”+url.getFile()); System.out.println(“getQuery():”+url.getQuery()); // int port =getPort(); // if(port == -1) //如果不写8080,port就是-1,我们就给他一个默认的值 // { // port = 80; // } } } //String getFile() //获取此URL的文件名 //String getHost() //获取此URL的主机名(如果适用)。 //String getPath() //获取此URL的路径部分 //int getPort() //获取此URL的端口号 //String getProtovol() //获取此URL的协议名称 //String getQuery() //获取此URL的查询部
//代码2 import java.net.*; import java.io.*; class URLConnectionDemo { public static void main(String[] args)throws Exception { URL url = new URL(“http://192.168.1.254:8080/myweb/demo.html”); //public URLConnection openConnection()throws IOException //返回一个URLConnection对象,它表示到URL所引用的远程对象的连接, //每次调用此URL的协议处理程序的openConnection方法都打开一个新的连接//内部封装了连接,不用再连接 URLConnection conn = url.openConnection(); System.out.println(conn); imputStream in = conn.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); System.out.println(new String(buf, 0 ,len)); } }
二十.网络编程小知识点
Inetaddress 用的是IP之地InetSocketAddress 用的是IP+端口号
以前都是分开写Socket(InetAddress address , int port)
Server Socket(int port , int backlog);
backlog - 队列的最大长度 (也就是允许连上的客户端数(最大连接数))
二十一.网络编程-域名解析
C:\Windows\System32\drivers\etc可以去这个地方去改变对应关系相关文章推荐
- 黑马程序员_毕向东_Java基础_DAY23-24_网络编程
- Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)
- 黑马程序员_Java基础_网络编程(下)_24
- Java高手真经. 编程基础卷:Java核心编程技术:Java基础+核心库+图形+网络+高级特性
- Java学习笔记之网络编程基础-获取本机名称
- java基础整理12--网络编程
- Java网络编程基础 InetAddress类的使用
- Java编程--网络编程基础
- Java套接字实现网络编程之基础篇(1)
- 实训 Java基础知识---流,线程,网络编程
- JAVA网络编程基础
- 基于Socket的Java网络编程集粹-Java基础-Java-编程开发
- [零基础学JAVA]Java SE应用部分-32.Java网络编程 推荐
- Java Socket网络编程基础
- Java网络编程基础 InetAddress类的使用
- Java网络编程基础 InetAddress类的使用
- Java在Client/Server网络中的应用-Java基础-Java-编程开发
- Java网络编程基础 Datagram类使用方法
- 网络-两远程客户端之间的通讯原理-Java基础-Java-编程开发
- Java 网络编程基础总结