黑马程序员-笔记-11-网络编程

来源:互联网 发布:ubuntu wine 安装软件 编辑:程序博客网 时间:2024/06/05 19:37

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

java中的网络模型:
    TCP/IP:自上至下分为:应用层,传输层,网络层,网际层。 

结合代码:UDP与TCP的区别,以及UDP传输的基本代码。

public class Play38 {/** * @throws IOException  * 网络编程: * UDP:面向无连接的。 * 数据封装在数据包中, * 每个包大小最大64K, * 无连接不可靠。但速度快。 *  *  * TCP:面向连接, * 形成数据通道,数据不限大小。 * 一次传输,三次握手, * 建立连接导致速度降低。 *  * Socket:为网络服务停工的一种机制。 * 通信的两端都有Socket。网络通信就是Socket的通信。 * 两个Socket通过IO流传输。 *  * UDP的套接字Socket:DatagramSocket * UnknownHostException 未知主机异常。 *  * @throws  */public static void main(String[] args) throws IOException,InterruptedException  {new Thread(){@Overridepublic void run() {try {UDPGet();} catch (IOException e) {e.printStackTrace();}};}.start();//for(int i=0;i<10;i++){//Thread.sleep(1000);//UDPSend();//}UDPSend2();}public static void test() throws UnknownHostException{InetAddress ia = InetAddress.getLocalHost();//获取本机主机名和地址。String address= ia.getHostAddress();//获取主机名称。String name = ia.getHostName();System.out.println(ia+":::"+address+":::"+name);InetAddress iaAddress = InetAddress.getByName("www.baidu.com");//通过主机名或者ip地址,获得其InetAddressSystem.out.println(iaAddress.getHostAddress());//建议使用地址,使用主机名,有解析过程。InetAddress[] ias = iaAddress.getAllByName("www.baidu.com");//通过主机名,获取器全部ip。System.out.println(ias.length);for(InetAddress ia1 : ias){System.out.println(ia1.getHostAddress());}}/* * UDP传输思路: * 建立UDPScoket服务 * 提供并封装数据 * 使用Socket的发送功能发送数据 * 关闭资源。 *  */public static void UDPSend() throws IOException{System.out.println("send++++");//创建UPD服务,建立对应的Socket对象。DatagramSocket ds = new DatagramSocket();//提供数据,封装成包。byte[] data = "UDP send message test,测试。".getBytes();DatagramPacket dp = new DatagramPacket(data, data.length,InetAddress.getLocalHost(),10000);//通过send方法,发送数据。ds.send(dp);//关闭资源。ds.close();}/* * UDP接收数据。 * UDP的接收端是阻塞式方法。 * 定义UDPSocket服务, * 定义数据包,因为要存储接收到的字节数据,因为数据包对象有更多功能提取字节数据中的不同数据信息。 * 通过socket的receive方法将收到数据封装在定义的数据包中。 * 通过数据包的功能,打印数据 * 关闭资源。 *  */public static void UDPGet() throws IOException{DatagramSocket ds = new DatagramSocket(10000);//服务不能建立在while中,否则端口异常,同时使用同一个端口。while(true){byte[] data = new byte[1024];DatagramPacket dp = new DatagramPacket(data, data.length);ds.receive(dp);//该方法如果没有接收到数据,线程阻塞。String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String str = new String(dp.getData(),0,dp.getLength());System.out.println(ip+"|||"+port+"|||"+str);}//ds.close();}} TCP传输的基本代码: public class Play39 {/** *TCP:对应客户端与服务端。 * *客户端对应的是:Socket *通过查阅Socket对象,发现在该对象建立时,就可以去连接指定主机。 *TCP是面向连接,所以建立Socket时,就要服务端已经存在,并连接成功,形成通路 *在该通道上就行数据传输。 * *服务端对应的是:ServerSocket * @throws IOException  * @throws UnknownHostException  */public static void main(String[] args) throws UnknownHostException, IOException {new Thread(){@Overridepublic void run() {try{server();//服务端一定要先启动。}catch (Exception e) {}};}.start();client();}/*客户端。 *  *1.创建Socket服务。指定连接的主机和端口。 *2.创建流。 *3.操作。 *  */public static void client() throws UnknownHostException, IOException{//创建客户端SocketSocket s = new Socket(InetAddress.getLocalHost(),10001);//发出数据,获取输出流。OutputStream os = s.getOutputStream();os.write("TCP send Test! Server,你好啊。".getBytes());//接受服务端的响应,使用输入流InputStream is = s.getInputStream();byte[] data = new byte[1024];int length = is.read(data);System.out.println(new String(data,0,length));s.close();}/* * 服务端 * 创建ServerSocket对象,并监听端口。 * 获取链接过来的客户端对象。没有链接过来就等待,是一个阻塞式的方法。 * 通过客户端Socket对象获得流,从而获得数据。 */public static void server() throws IOException, InterruptedException {ServerSocket ss = new ServerSocket(10001);Socket s = ss.accept();InputStream is = s.getInputStream();byte[] data = new byte[1024];int length = is.read(data);System.out.println(new String(data,0,length)+"|||"+s.getPort()+"+++"+s.getInetAddress());//使用服务端给客户端响应OutputStream os = s.getOutputStream();Thread.sleep(10000);os.write("Get Message,roger".getBytes());s.close();//ss.close();//在现实中,ServerSocket是没有必要关闭,他需要继续接受别的请求。}}使用TCP实现一个类似聊天室的功能。public class Play40 {public static void main(String[] args) throws UnknownHostException, IOException {new Thread(){@Overridepublic void run() {try{server();}catch (Exception e) {}};}.start();client();}public static void client() throws UnknownHostException, IOException{Socket s = new Socket(InetAddress.getLocalHost(),10001);PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//使用打印流,可以取代缓冲流刷新,以及继续换行的作用。//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));BufferedReader brs = new BufferedReader(new InputStreamReader(s.getInputStream()));BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));String line = null;while((line=br.readLine())!=null){if(line.equals("end"))break;pw.println(line);System.out.println(brs.readLine());}pw.close();br.close();brs.close();s.close();}public static void server() throws IOException, InterruptedException {ServerSocket ss = new ServerSocket(10001);Socket s = ss.accept();System.out.println(s.getInetAddress());BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));String str = null;while((str=br.readLine())!=null){System.out.println(str);Thread.sleep(100);bw.write(str.toUpperCase());bw.newLine();//在一行数据发送完毕,接收端,需要接收到回车符,才能知道一次数据接受完毕。所以需要使用newLine方法。bw.flush();//BufferedWriter是一个具有缓冲作用的流,需要刷新将一次的数据读入。}s.close();ss.close();}}