Java基础——网络编程
来源:互联网 发布:淘宝拍摄场景布置 编辑:程序博客网 时间:2024/05/21 18:09
1. 网络编程
网络通讯
1. 网络模型:
• OSI参考模型:开放系统互联参考模型(Open System InterConnection)
• TCP/IP参考模型:传输控制协议/互联网协议(Transmission Control Protocol/InternetProtocol)
Java Web主要涉及应用层;
传输层常见协议是TCP、UDP;
网际层常见协议是IP;
应用层常见协议是http、ftp;
2. 网络通讯要素
IP地址:InetAddress
•网络中设备的标识
•不易记忆,可用主机名
•本地回环地址: 127.0.0.1主机名(就是网址): localhost
具有全球唯一性,相对于internet,IP为逻辑地址。
注意:
192.168.1.0和192.168.1.255不能用。.0代表网络段,.255代表这个段的广播地址
IP地址相关使用案例
请看下面示例:
class IPDemo{ publicstaticvoid main(String[] args) throws Exception { //获取本机IP信息 //InetAddress i = InetAddress.getLocalHost(); // System.out.println(i.toString());// System.out.println("address:"+i.getHostAddress());// System.out.println("name:"+i.getHostName()); //获取任意主机IP信息,以IP地址为主,主机名需要解析 InetAddress ia = InetAddress.getByName("thinkpad-sl400"); System.out.println("address:"+ia.getHostAddress()); System.out.println("name:"+ia.getHostName()); }}<span style="font-family:Calibri;font-size:14px;"> </span>
端口号:用于标识进程的逻辑地址,不同进程的标识
•有效端口: 0~65535,其中0~1024系统使用或保留端口。
•数据要发送到对方指定的应用程序上,为了标识这些应用程序,所以给这些网络应用程序都用数字进行标识。为了方便称呼这个数字,叫做端口。逻辑端口。
传输协议: 为了进行网络中的数据交换(通信)而建立的规则、标准或约定。
•国际组织定义了通用协议TCP/IP。
•常见协议: TCP, UDP
网络架构
C/S:Client/Server
客户端,服务端。
特点:
1,需要在客户端和服务端都需要按照编写的软件。
2,维护较麻烦。
好处:可以减轻服务端的压力,如网络游戏。
B/S:Browser/Server
浏览器,服务端。
1,客户端不用单独编写软件。
因为客户端用的就是浏览器。
2,对于软件升级,只要考虑服务端即可。
弊端:所有的程序都运行在服务端,客户端的浏览器毕竟解析能力较弱。对游戏等。
UDP传输
1. 概念
2. 特点
•将数据及源和目的封装成数据包中,不需要建立连接
•每个数据报的大小在限制在64k内
•因无连接,是不可靠协议(容易丢失数据包)
•不需要建立连接,速度快
应用:网络游戏,视频会议,聊天,桌面共享等
DatagramSocket:
数据报套接字是包投递服务的发送或接收点(邮局,码头)
此类表示用来发送和接收数据报包的套接字。
3. 怎么使用?
1) DatagramSocket与DatagramPacket
2) 建立发送端,接收端。
3) 建立数据包。
4) 调用Socket的发送接收方法。
5) 关闭Socket。
发送端与接收端是两个独立的运行程序。
UDP传输基础
示例:
/*需求:通过udp传输方式,将一段文字数据发送出去。,定义一个udp发送端。思路:1,建立updsocket服务。(端点:邮局)2,提供数据,并将数据封装到数据包中。3,通过socket服务的发送功能,将数据包发出去。4,关闭资源。只运行发送端,数据丢失 */ class UdpSend{ publicstaticvoid main(String[] args) throws Exception { //1,创建udp服务。通过DatagramSocket对象。 DatagramSocket ds = new DatagramSocket(8888); //2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) byte[] buf = "udp ge men lai le ".getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName ("192.168.1.254"),10000); //3,通过socket服务,将已有的数据包发送出去。通过send方法。 ds.send(dp); //4,关闭资源。 ds.close(); }} /*需求:定义一个应用程序,用于接收udp协议传输的数据并处理的。 定义udp的接收端。思路:1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。 方便于明确哪些数据过来该应用程序可以处理。 2,定义一个数据包,因为要存储接收到的字节数据。因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。5,关闭资源。 */ class UdpRece{ publicstaticvoid main(String[] args) throws Exception { //1,创建udp socket,建立端点。 ////这句不能加入循环,发生BindException(绑定异常),同个端口被不同的Socket使用 DatagramSocket ds = new DatagramSocket(10000); //连续接收发送端的信息while(true) { //2,定义数据包。用于存储数据。 byte[] buf = newbyte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); //3,通过服务的receive方法将收到数据存入数据包中。 ds.receive(dp);//阻塞式方法。没数据就等待 //4,通过数据包的方法获取其中的数据。 String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(),0,dp.getLength()); int port = dp.getPort(); System.out.println(ip+"::"+data+"::"+port); } //5,关闭资源 //ds.close(); }}
UDP传输-键盘录入
192.168.1.255中的.255是广播地址,任意接收端都能接收到数据
如:
class UdpSend2{ publicstaticvoid main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//System.in阻塞式方法 String line = null; while((line=bufr.readLine())!=null) { if("886".equals(line)) break; byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName ("192.168.1.255"),10001); ds.send(dp); } ds.close(); }} class UdpRece2{ publicstaticvoid main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(10001); while(true) { byte[] buf = newbyte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); ds.receive(dp);//阻塞式方法 String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(),0,dp.getLength()); System.out.println(ip+"::"+data); } }}
UDP传输-聊天程序
/*编写一个聊天程序。有收数据的部分,和发数据的部分。这两部分需要同时执行。那就需要用到多线程技术。一个线程控制收,一个线程控制发。 因为收和发动作是不一致的,所以要定义两个run方法。而且这两个方法要封装到不同的类中。 */class SendClient implements Runnable{ private DatagramSocket ds; public SendClient(DatagramSocket ds) { this.ds = ds; } publicvoid run() { try { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String line = null; while((line=buf.readLine())!=null) { byte by[] = line.getBytes(); DatagramPacket dp = new DatagramPacket(by,by.length, InetAddress.getByName("127.0.0.1"),10008); ds.send(dp); if(line.equals("exit")) break; } ds.close(); } catch(Exception e) { thrownew RuntimeException("发送失败"); } }}class RecClient implements Runnable{ private DatagramSocket Recds; public RecClient(DatagramSocket Recds) { this.Recds = Recds; } publicvoid run() { try { while(true) { byte buf[] = newbyte[1024]; DatagramPacket Recdp = new DatagramPacket(buf,buf.length); Recds.receive(Recdp); String IP = Recdp.getAddress().getHostAddress(); String data = new String(Recdp.getData(),0,Recdp.getLength()); if(data.equals("exit")) { System.out.println(IP+",离开聊天室"); break; } System.out.println("ip="+IP+",data={"+data+"}"); } } catch(Exception e1) { thrownew RuntimeException("接收失败"); } }}class test{ publicstaticvoid main(String[] args) throws Exception { DatagramSocket sendSocket = new DatagramSocket(); DatagramSocket RecSocket = new DatagramSocket(10008); new Thread(new SendClient(sendSocket)).start(); new Thread(new RecClient(RecSocket)).start(); }}
TCP传输
1. 概念
2. 特点
•建立连接,形成传输数据的通道。
•在连接中进行大数据量传输
•通过三次握手(A发送,B响应,A回应)完成连接,是可靠协议
•必须建立连接,效率会稍低
应用:下载数据
3. 怎么使用?
客户端-基本思路
客户端需要明确服务器的ip地址以及端口,这样才可以去试着建立连接,如果连接失败,会出现异常。
连接成功,说明客户端与服务端建立了通道,通过IO流就可进行数据的传输,而Socket对象已提供了输入流和输出流对象,通过getInputStream(),getOutputStream()获取即可。
与服务端通讯结束后,关闭Socket。
服务端-基本思路
服务端需要明确它要处理的数据是从哪个端口进入的。
当有客户端访问时,要明确是哪个客户端,可通过accept()获取已连接的客户端对象,并通过该对象与客户端通过IO流进行数据传输。
当该客户端访问结束,关闭该客户端。
客户端与服务器端是两个独立的应用程序。
服务器端怎么识别各个客户端?
服务器端能获取客户端对象,通过客户端对象的输出输入流,识别各个客户端。
TCP传输-基础案例
/*演示tcp传输。 1,tcp分客户端和服务端。2,客户端对应的对象是Socket。 服务端对应的对象是ServerSocket。 */ /*客户端,通过查阅socket对象,发现在该对象建立时,就可以去连接指定主机。因为tcp是面向连接的。所以在建立socket服务时,就要有服务端存在,并连接成功。形成通路后,在该通道进行数据的传输。 需求:给服务端发送给一个文本数据。 步骤:1,创建Socket服务。并指定要连接的主机和端口。 服务器端怎么识别各个客户端?服务器端能获取客户端对象,通过客户端对象的输出输入流,识别各个客户端。 */import java.io.*;import java.net.*;class TcpClient{ publicstaticvoid main(String[] args) throws Exception { //创建客户端的socket服务。指定目的主机和端口,连接成功后,有Socket流 Socket s = new Socket("12.0.0.1",10098); //通过空构造函数创建Socket对象 /*Socket s = new Socket(); InetSocketAddress is = new InetSocketAddress("127.0.0.1",10098); s.connect(is);*/ //为了发送数据,应该获取socket流中的输出流。 OutputStream out = s.getOutputStream(); out.write("tcp ge men lai le ".getBytes()); s.close(); }} /*需求:定义端点接收数据并打印在控制台上。 服务端:1,建立服务端的socket服务。ServerSocket(); 并监听一个端口。2,获取连接过来的客户端对象。 通过ServerSokcet的 accept方法。没有连接就会等,所以这个方法阻塞式的。3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流来读 取发过来的数据。 并打印在控制台。 4,关闭服务端。(可选) */class TcpServer{ publicstaticvoid main(String[] args) throws Exception { //建立服务端socket服务。并监听一个端口,指定能连接该服务端的IP为5个。 ServerSocket ss = new ServerSocket(10098,5); //通过accept方法获取连接过来的客户端对象。 while(true) { Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+".....connected"); //获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据。 InputStream in = s.getInputStream();//这个源不是硬盘也不是键盘录入,是网络流 byte[] buf = newbyte[1024]; int len = in.read(buf); System.out.println(new String(buf,0,len)); s.close();//关闭客户端. } //ss.close(); }}
TCP传输-客户端和服务端互访
/*演示tcp的传输的客户端和服务端的互访。 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息。*/ /*客户端:1,建立socket服务。指定要连接主机和端口。2,获取socket流中的输出流。将数据写到该流中。通过网络发送给服务端。3,获取socket流中的输入流,将服务端反馈的数据获取到,并打印。4,关闭客户端资源。*/class TcpClient2 { publicstaticvoid main(String[] args)throws Exception { Socket s = new Socket("127.0.0.1",10098); OutputStream out = s.getOutputStream(); out.write("Server,你好".getBytes()); InputStream in = s.getInputStream(); byte[] buf = newbyte[1024]; int len = in.read(buf);//阻塞式方法,读取服务端发过来的数据 System.out.println(new String(buf,0,len)); s.close(); }} class TcpServer2{ publicstaticvoid main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10098); while(true) { Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println("ip="+ip+"....connected"); InputStream in = s.getInputStream();//获取客户端的读取流来读取数据 byte[] buf = newbyte[1024]; int len = in.read(buf);//读取客户端发过来的数据 System.out.println(new String(buf,0,len)); OutputStream out = s.getOutputStream();//获取客户端的输出流来写反馈信息 Thread.sleep(10000); out.write("Client,你好".getBytes()); s.close(); } //ss.close(); }}
TCP传输-文本转换服务器示例
/* 需求:建立一个文本转换服务器。客户端给服务端发送文本,服务单会将文本转成大写在返回给客户端。而且客户端可以不断的进行文本转换。当客户端输入over时,转换结束。 分析:客户端:既然是操作设备上的数据,那么就可以使用io技术,并按照io的操作规律来思考。源:键盘录入。目的:网络设备,网络输出流。而且操作的是文本数据。可以选择字符流。 步骤1,建立服务。2,获取键盘录入。3,将数据发给服务端。4,获取服务端返回的大写数据。5,结束,关资源。 都是文本数据,可以使用字符流进行操作,同时提高效率,加入缓冲。 */import java.io.*;import java.net.*; class TransClient{ publicstaticvoid main(String[] args) throws Exception { Socket s = new Socket("192.168.1.254",10005); //定义读取键盘数据的流对象。 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); //定义目的,将数据写入到socket输出流。发给服务端。 //BufferedWriter bufOut = //new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); //定义一个socket读取流,读取服务端返回的大写信息。 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line=bufr.readLine())!=null) { if("over".equals(line)) break; out.println(line);// bufOut.write(line);//数据在缓冲里,没有刷到输出流// bufOut.newLine();// bufOut.flush(); String str =bufIn.readLine(); System.out.println("server:"+str); } bufr.close(); s.close();//Socket流里加"-1",结束标记 }}/* 服务端:源:socket读取流。目的:socket输出流。都是文本,装饰。 */ class TransServer{ publicstaticvoid main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10005); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"....connected"); //读取socket读取流中的数据。 BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); //目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。 //BufferedWriter bufOut = //new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; //当客户端Socket流关闭,readline()方法读取到结束标记,结束循环,服务端Socket流关闭 while((line=bufIn.readLine())!=null)//readLine方法要读取到客户端数据的换行标记才不阻塞 { System.out.println(line); out.println(line.toUpperCase());// bufOut.write(line.toUpperCase());// bufOut.newLine();// bufOut.flush(); } s.close(); ss.close(); }}/*该例子出现的问题。现象:客户端和服务端都在莫名的等待。为什么呢?因为客户端和服务端都有阻塞式方法。这些方法没有读到结束标记newline()的结束标记。那么就一直等,而导致两端,都在等待。*/
TCP复制文件(上传文件)示例
客户端连接上服务端,两端都在等待,没有任何数据传输。
通过例程分析:
•因为read方法或者readLine方法是阻塞式。
解决办法:
•自定义结束标记
•使用shutdownInput, shutdownOutput方法。
代码实现如下:
class TextClient{ publicstaticvoid main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1",10098); BufferedReader bufr = new BufferedReader(new FileReader("c:/t1.java")); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; while((line=bufr.readLine())!=null) { out.println(line); } //out.println("over");//自定义标记法,容易与文本的内容重复,文件没有"over"的前提下才可用 s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1. BufferedReader bufIn = new BufferedReader(new InputStreamReader (s.getInputStream())); String str = bufIn.readLine();//重新打开输入流 System.out.println(str); bufr.close(); s.close(); }}class TextServer{ publicstaticvoid main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10098); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip+"....connected"); BufferedReader bufIn = new BufferedReader(new InputStreamReader (s.getInputStream())); PrintWriter out = new PrintWriter(new FileWriter("c:/server.txt"),true); String line = null; while((line=bufIn.readLine())!=null) { //if("over".equals(line)) //break; out.println(line); } PrintWriter pw = new PrintWriter(s.getOutputStream(),true); pw.println("上传成功"); out.close(); s.close(); ss.close(); }}
URLDecoder和URLEncoder
用于普通字符串和application/x-www-form-urlencoded MIME字符串之间的转换;
当URL地址里包含非西欧字符的字符串时,系统会将这些非西欧字符的字符串转换成application/x-www-form-urlencoded MIME字符串。
URLDecoder: HTML 格式解码的实用工具类。该类包含了将 String 从 application/x-www-form-urlencoded MIME 格式解码的静态方法。
static String decode(String s, String enc)
使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码。
String u2 = URLDecoder.decode("%D6%D0%B9%FA","GBK");
System.out.println(u2);
URLEncoder: HTML 格式编码的实用工具类。该类包含了将 String 转换为application/x-www-form-urlencoded
MIME格式的静态方法。
static String encode(String s, String enc)
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。
String u1 = URLEncoder.encode("中国","GBK");
System.out.println(u1);
TCP传输-客户端并发上传图片示例
/*需求:上传图片。*//*客户端。1,服务端点。2,读取客户端已有的图片数据。3,通过socket 输出流将数据发给服务端。4,读取服务端反馈信息。5,关闭。*/ import java.io.*;import java.net.*;class test{ publicstaticvoid main(String[] args)throws Exception { if(args.length!=1) { System.out.println("请选择一个jpg格式的图片"); return ; } File file = new File(args[0]);//在主函数中传入参数 if(!(file.exists() && file.isFile())) { System.out.println("该文件有问题,要么不存在,要么不是文件"); return ; } if(!file.getName().endsWith(".jpg")) { System.out.println("图片格式错误,请重新选择"); return ; } if(file.length()>1024*1024*5) { System.out.println("文件过大,没安好心"); return ; } Socket s = new Socket("127.0.0.1",10089); FileInputStream fis = new FileInputStream(file); OutputStream out = s.getOutputStream(); byte[] buf = newbyte[1024]; int len = 0; while((len=fis.read(buf))!=-1) { out.write(buf,0,len); } //告诉服务端数据已写完 s.shutdownOutput(); InputStream in = s.getInputStream(); byte[] bufIn = newbyte[1024]; int num = in.read(bufIn); System.out.println(new String(bufIn,0,num)); fis.close(); s.close(); }} /*服务端 这个服务端有个局限性。当A客户端连接上以后。被服务端获取到。服务端执行具体流程。这时B客户端连接,只有等待。因为服务端还没有处理完A客户端的请求,还没有循环回来执行下次accept方法。所以暂时获取不到B客户端对象。 那么为了可以让多个客户端同时并发访问服务端。那么服务端最好就是将每个客户端封装到一个单独的线程中,这样,就可以同时处理多个客户端请求。 如何定义线程呢? 只要明确了每一个客户端要在服务端执行的代码即可。将该代码存入run方法中。*/ class PicThread implements Runnable{ private Socket s; PicThread(Socket s) { this.s = s; } publicvoid run() { int count = 1;//为什么不定义全局变量?多个线程共享此数据,导致多个客户端共用此变量,每个客户端产生的文件名断续,而且线程不安全 String ip = s.getInetAddress().getHostAddress(); try { System.out.println(ip+"....connected"); InputStream in = s.getInputStream(); File dir = new File("c:\\"); File file = new File(dir,ip+"("+(count)+")"+".jpg"); while(file.exists()) file = new File(dir,ip+"("+(count++)+")"+".jpg"); FileOutputStream fos = new FileOutputStream(file); byte[] buf = newbyte[1024]; int len = 0; while((len=in.read(buf))!=-1) { fos.write(buf,0,len); } OutputStream out = s.getOutputStream(); out.write("上传成功".getBytes()); fos.close(); s.close(); } catch (Exception e) { thrownew RuntimeException(ip+"上传失败"); } }} class Demo{ publicstaticvoid main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10089); while(true) { Socket s = ss.accept();//主线程等待 new Thread(new PicThread(s)).start(); } //ss.close(); }}
TCP传输-客户端并发登陆示例
/*客户端通过键盘录入用户名。服务端对这个用户名进行校验。 如果该用户存在,在服务端显示xxx,已登陆。并在客户端显示 xxx,欢迎光临。 如果该用户存在,在服务端显示xxx,尝试登陆。并在客户端显示 xxx,该用户不存在。 最多就登录三次。*/import java.io.*;import java.net.*;class test{ publicstaticvoid main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1",10089); BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(s.getOutputStream(),true); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); for(int x=0; x<3; x++) { String line = bufr.readLine(); if(line==null) break; out.println(line); String info = bufIn.readLine(); System.out.println("info:"+info); if(info.contains("欢迎")) break; } bufr.close(); s.close(); }} class UserThread implements Runnable{ private Socket s; UserThread(Socket s) { this.s = s; } publicvoid 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())); String name = bufIn.readLine();//客户端输入为空,name=null,应break处理; if(name==null) break; BufferedReader bufr = new BufferedReader(new FileReader("c:/user.txt")); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String line = null; boolean flag = false;//判断标记进行判断 while((line=bufr.readLine())!=null) { if(line.equals(name)) { flag = true; break; } } if(flag) { System.out.println(name+",已登录"); out.println(name+",欢迎光临"); break;//结束循环 } else { System.out.println(name+",尝试登录"); out.println(name+",用户名不存在"); } } s.close(); } catch (Exception e) { thrownew RuntimeException(ip+"校验失败"); } }}class Demo{ publicstaticvoid main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10089); while(true) { Socket s = ss.accept(); new Thread(new UserThread(s)).start(); } }}
浏览器客户端-自定义服务端
1. 在命令行运行服务端程序;
2. 在浏览器中输入http://主机名:端口;
3. 浏览器中返回服务端给的数据;
实现方式如下:
/*演示客户端和服务端。 客户端:浏览器 (telnet IP地址端口:远程登录工具,可以连接网络中任意一台主机,对主机进行命令式的配置)服务端:自定义。 客户端:自定义。(图形界面)服务端:Tomcat服务器。 */ class ServerDemo { publicstaticvoid 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(); }} 浏览器-Tomcat服务器客户端:浏览器。服务端:Tomcat服务器。1) 打开startup.bat,启动Tomcat服务器;2) 在浏览器中输入http://127.0.0.1:8080即可访问Tomcat服务器欢迎界面;3) 在webapps文件里面新建文件A,在A文件夹里创建HTML文件;4) 在浏览器输入http://127.0.0.1:8080/A/demo.html即可访问Tomcat提供的网页请看如下示例:class ServerDemo { publicstaticvoid 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 = newbyte[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='red' size='7'>客户端你好</font>"); s.close(); ss.close(); }}/* 在浏览器输入:http://192.168.1.254:11000/myweb/demo.html 标准浏览器发给Tomcat的信息(HTTP的请求消息头) GET /myweb/demo.html HTTP/1.1(协议版本)Accept: application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel,application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD,(能接收的数据格式)Accept-Language: zh-cnAccept-Encoding: gzip, deflate(浏览器告诉服务器支持的数据封装形式)User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)Host: 192.168.1.254:11000Connection: Keep-Alive(连接状态)空行隔开信息头和数据体 请求数据体*/ 自定义浏览器-Tomcat服务器示例 class MyIE //自定义浏览器发信息给Tomcat{ publicstaticvoid main(String[] args)throws Exception { Socket s = new Socket("127.0.0.1",8080); PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("GET /myweb/demo.html HTTP/1.1"); out.println("Accept: */*"); out.println("Accept-Language: zh-cn"); out.println("Host: 127.0.0.1:11000"); out.println("Connection: closed"); out.println();//请求头与资源之间用行隔开 out.println(); //反馈浏览器的请求信息(数据体和消息头) BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line=bufr.readLine())!=null) { System.out.println(line); } s.close(); }} /*Tomcat服务器反馈回自定义浏览器的http应答信息头HTTP/1.1 200 OKServer: Apache-Coyote/1.1ETag: W/"51-1430663059963"Last-Modified: Sun, 03 May 2015 14:24:19 GMTContent-Type: text/htmlContent-Length: 51Date: Sun, 03 May 2015 15:02:16 GMTConnection: close空行隔开<html><body><h1>我的主页</h1></body></html> 问题:如何消除应答信息头的内容,只显示数据体呢?用URL和URLConnection类 */
自定义图形界面浏览器-Tomcat服务端示例
class MyIEByGUI{ private Frame f; private TextField tf; private Button but; private TextArea ta; private Dialog d; private Label lab; private Button okBut; MyIEByGUI() { init(); } publicvoid 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); f.add(tf); f.add(but); f.add(ta); myEvent(); f.setVisible(true); } privatevoid myEvent() { okBut.addActionListener(new ActionListener() { publicvoid actionPerformed(ActionEvent e) { d.setVisible(false); } }); d.addWindowListener(new WindowAdapter() { publicvoid windowClosing(WindowEvent e) { d.setVisible(false); } }); tf.addKeyListener(new KeyAdapter() { publicvoid keyPressed(KeyEvent e) { try { if(e.getKeyCode()==KeyEvent.VK_ENTER) showDir(); } catch (Exception ex) { } } }); but.addActionListener(new ActionListener() { publicvoid actionPerformed(ActionEvent e) { try { showDir(); } catch (Exception ex) { } } }); f.addWindowListener(new WindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); } privatevoid showDir()throws Exception { ta.setText(""); String url = tf.getText();//http://192.168.1.254:8080/myweb/demo.html int index1 = url.indexOf("//")+2; int index2 = url.indexOf("/",index1); String str = url.substring(index1,index2); String[] arr = str.split(":"); String host = arr[0]; int port = Integer.parseInt(arr[1]); String path = url.substring(index2); //ta.setText(str+"...."+path); Socket s = new Socket(host,port); PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("GET "+path+" HTTP/1.1"); out.println("Accept: */*"); out.println("Accept-Language: zh-cn"); out.println("Host: 127.0.0.1:11000"); out.println("Connection: closed"); out.println(); out.println(); BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while((line=bufr.readLine())!=null) { ta.append(line+"\r\n"); } s.close(); } publicstaticvoid main(String[] args) { new MyIEByGUI(); }}返回信息包含应答信息头,可通过URL优化;实例
URL-URLConnecttion
URL概念
URL对象常用方法:
URL怎么使用?
class URLDemo { publicstaticvoid main(String[] args) throws MalformedURLException { URL url = new URL("http://192.168.1.254/myweb/demo.html?name=haha&age=30"); System.out.println("getProtocol() :"+url.getProtocol()); 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()); /*当url没有给出port时候 * int port = getPort(); if(port==-1) port = 80; getPort()==-1 */ }}
URLConnection概念
抽象类 URLConnection是所有类的超类,它代表应用程序和 URL之间的通信链接。此类的实例可用于读取和写入此 URL引用的资源。
URLConnection解析应答信息头,拆包原理
URLConnection怎么使用?
基本应用:
class test{ publicstaticvoid main(String[] args) throws Exception { URL url = new URL("http://127.0.0.1:8080/myweb/demo.html"); URLConnection conn = url.openConnection(); //在内部做了连接到服务器的动作,不用创建Socket了 System.out.println(conn); InputStream in = conn.getInputStream(); byte[] buf = newbyte[1024]; int len = in.read(buf); System.out.println(new String(buf,0,len)); }}<span style="font-family:Calibri;BACKGROUND-COLOR: #ffffff"></span>
URLConnection自定义图形界面浏览器-Tomcat服务端
class MyIEByGUI{ private Frame f; private TextField tf; private Button but; private TextArea ta; private Dialog d; private Label lab; private Button okBut; MyIEByGUI() { init(); } publicvoid 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); f.add(tf); f.add(but); f.add(ta); myEvent(); f.setVisible(true); } privatevoid myEvent() { okBut.addActionListener(new ActionListener() { publicvoid actionPerformed(ActionEvent e) { d.setVisible(false); } }); d.addWindowListener(new WindowAdapter() { publicvoid windowClosing(WindowEvent e) { d.setVisible(false); } }); tf.addKeyListener(new KeyAdapter() { publicvoid keyPressed(KeyEvent e) { try { if(e.getKeyCode()==KeyEvent.VK_ENTER) showDir(); } catch (Exception ex) { } } }); but.addActionListener(new ActionListener() { publicvoid actionPerformed(ActionEvent e) { try { showDir(); } catch (Exception ex) { } } }); f.addWindowListener(new WindowAdapter() { publicvoid windowClosing(WindowEvent e) { System.exit(0); } }); } privatevoid showDir()throws Exception { ta.setText(""); String urlPath = tf.getText();//http://192.168.1.254:8080/myweb/demo.html URL url = new URL(urlPath); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); byte[] buf = newbyte[1024]; int len = in.read(buf); ta.setText(new String(buf,0,len)); } publicstaticvoid main(String[] args) { new MyIEByGUI(); }}
域名解析
原理图:
- Java基础—网络编程
- Java基础——网络编程
- Java基础(十三)——网络编程
- JAVA基础——网络编程
- Java基础——网络编程
- Java基础——网络编程
- Java基础——网络编程
- java基础——网络编程
- JAVA基础——网络编程
- java基础——GUI、网络编程
- Java基础——网络编程
- java基础——网络编程
- JAVA基础——网络编程
- 【java基础】——网络编程
- Java基础——网络编程
- 网络编程——Java基础
- Java基础11——网络编程
- Java基础(十三)——网络编程
- nginx.conf 配置文件中文说明
- Single Number
- UVALIVE 3971 Assemble 二分+贪心
- Html5用Canvas制作绘图板
- TCP/IP概述
- Java基础——网络编程
- DispatcherTimer 停止运行了?
- linux 下安装lua 问题
- LeetCode | Palindrome Number(回文数字)
- java文件路径操作详细(转载)
- 基于LBP的背景建模算法
- R6034错误解决办法
- 液晶显示屏-电子时钟
- Android 打包签名 从生成keystore到完成签名 -- 转