黑马程序员之网络编程

 

---------------------- android培训java培训、期待与您交流! ----------------------

1. 找到对方IP
2. 数据要发送给对方指定的应用程序上,为了标识这些应用程序,所以给这些网络应用程序应用程序都用
   数字进行标识,为了方便称呼这个数字,叫做端口。逻辑端口
3  定义通信规则。这个通讯规则称为协议
   国际组织定义了通用协议 TCP/IP    
4  端口范围 0到65535  其中0到1024系统使用或保留端口 
   本地回环地址 127.0.0.1 主机名 localhost 

5 网线,光纤,无线是物理层 http 是应用层协议
6 IP
    (1)拿到本地主机的地址和名称 :
    InetAddress i= InetAddress.getLocalHost();
    System.out.println(i);
    System.out.println(i.getHostAddress());
    System.out.println(i.getHostName());
   
    (2) 拿到指定主机的IP地址和名称
    InetAddress ai= InetAddress.getByName("www.baidu.com");
    System.out.println("baidu IP : "+ai.getHostAddress());
    System.out.println("baidu Name : "+ai.getHostName());

7  UDP
   讲数据及源和目的封装成数据包中,不需要建立连接 
   每个数据报德大小在限制在64K内
   因无连接,是不可靠协议
   不需要建立连接,速度快

   TCP
   建立连接,形成传输数据的通道
   在连接中进行大数据量传输
   通过三次握手完成连接,是可靠协议
   必须建立连接,效率会稍低
   下载是TCP

   凡是带IP地址的构造函数都是用来发送


8  需求: 通过UDP传输方式,将一段文字数据发送出去
   思路:
    1 建立udpsocket服务
    2 提供数据,并将数据封装到数据包中
    3 通过socket 服务的发送功能,将数据包发出去
    4 关闭资源

  public class Udpsend {

 public static void main(String[] args) throws Exception {
       
  DatagramSocket ds = new DatagramSocket();
  byte[] buf= "Udpsend ".getBytes();
  
  DatagramPacket dp= new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),8888);
  
  ds.send(dp);
  System.out.println("success");
 }

  }
    

 9   需求:
     定义一个应用程序,用于接收udp协议传输的数据并处理的
   
     思路:
      1  定义udpsocket服务 。通常会监听一个端口,其实就是给这个接收网络应用程序定义数字标识
          方便与明确哪些数据过来该应用程序可以处理
      2  定义一个数据包,因为要存储接收到的字节数据
         因为数据包对象中有更多功能可以提取字节数据中的不同数据信息
      3  通过socket服务的receive 方法讲收到的数据库存入已定义好的数据包中
      4  通过数据包对象的特有功能,将这些不同的数据取出,打印在控制台上
      5  关闭资源 

public class Udpreceive {

 public static void main(String[] args) throws Exception {
       
  DatagramSocket ds= new DatagramSocket(8888);
  while(true){
  
  byte [] buf= new byte[1024];
   
  DatagramPacket dp= new DatagramPacket(buf,buf.length);
  ds.receive(dp);
  String ip= dp.getAddress().getHostAddress();
  byte[] ip2= dp.getAddress().getAddress();
  byte[] data = dp.getData();
  String data2= new String(data,0,dp.getLength());
  int port = dp.getPort();
  
  System.out.println("ip"+ip+","+port+","+data2);
  //ds.close();
  }
 }

}

10 TCP

   1 tcp 分客户端和服务端
   2  客户端对应的对象是socket
     服务端对应的对象是serversocket  


   客户端
   通过查阅socket对象,发现在该对象建立时,就可以去连接指定主机
   因为tcp是面向连接的,所以在建立socket服务时
   就要有服务端存在,并连接成功, 形成通路后,在该通道进行数据的传输

需求: 给服务端发送一个文本数据
  
   步骤:
   1 创建 socket服务, 并指定要连接的主机和端口
  package TCP;

import java.io.*;
import java.net.*;
public class TCPclient {
    
 public static void main(String[] args) throws Exception, Exception {
       
  Socket s = new Socket("192.168.1.122",9999);
   OutputStream out= s.getOutputStream();
   out.write("my tcp test".getBytes());
  
   s.close();
  
  
 }
}

 2 创建serversocket 服务端

package TCP;

import java.io.*;
import java.net.*;
public class TCPserver {

 public static void main(String[] args) throws Exception {
       
   ServerSocket ss= new ServerSocket(9999);
   Socket s=  ss.accept();
   byte [] buf= new byte[1024];
   InputStream in= s.getInputStream();
   int len = in.read(buf);
    String ip= s.getInetAddress().getHostAddress();
    String data=  new String(buf,0,len);
    System.out.println(ip+" : "+data);
 }

}


11 需求:建立一个文本转换服务器。
   客户端给服务端发送文本,服务单会讲文本装成大写在返回给客户端
   而且客户端可以不断的进行文本转换,当客户端输入over时,转换结束


   分析:
   客户端:
   既然是操作设备上的数据,那么久可以使用io技术,并按照io的操作规律来思考
   源: 键盘录入
  目的 : 网络设备,网络输出流
  而且操作的是文本数据,可以选择字符流  
 
 步骤 
   1 建立服务
      2 获取键盘录入
      3 将数据发给服务端
      4 后去服务端返回的大写数据
      5 结束,关资源
  
      都是文本数据,可以使用字符流进行操作,同时提高效率,加入缓冲

服务器端

import java.io.*;
import java.net.*;
public class TransTcpserver {

 public static void main(String[] args) throws Exception {
         
   ServerSocket ss= new ServerSocket(18888);
   Socket s= ss.accept();
  
   BufferedReader br= new BufferedReader(new InputStreamReader(s.getInputStream()));
  
   PrintWriter pw= new PrintWriter(s.getOutputStream(),true);
   String line;
   while((line=br.readLine())!=null){
   
    System.out.println("from client : "+line);
    pw.println(line.toUpperCase());
    if(line.equals("bye")){
     break;
    }
   
   }
  
   s.close();
   ss.close();
 }

}


客户端

package TCP3;

import java.io.*;
import java.net.*;
public class TransTcpclient {

 public static void main(String[] args) throws Exception, Exception {
      
  Socket s= new Socket("192.168.1.122",18888);
  
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  
  //StringWriter w= new StringWriter();
  BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

  BufferedReader brr=new BufferedReader(new InputStreamReader(s.getInputStream()));
  String line;
  while((line=br.readLine())!=null){
   
   bw.write(line);
   bw.newLine();
   bw.flush();
   
   String str= brr.readLine();
   System.out.println("收到服务端  : " +str);
   
  }
  
  s.close();
 }

}

 

11  需求 : 多个客户端上传图片  

 客户端 :

package MultipPic;

import java.io.*;
import java.net.*;
public class Client {

 public static void main(String[] args) throws Exception {
         
  
  File f= new File(args[0]);
  //File f= new File("G://2.jpg");
  Socket s= new Socket("192.168.1.122",8888);
  InputStream in= s.getInputStream();
  OutputStream out= s.getOutputStream();
  
  FileInputStream fs= new FileInputStream(f);
  
  byte [] buf= new byte[1024];
  int len ;
  while((len=fs.read(buf))!=-1){
   out.write(buf,0,len);
  }
  
  s.shutdownOutput();
  byte [] buf2= new byte[1024];
  int sum ;
  sum=in.read(buf2);
  System.out.println(new String(buf2,0,sum));
  
  fs.close();
  in.close();
  out.close();
        s.close();  
 }

}


服务器端 :

package MultipPic;

import java.net.*;
import java.io.*;
public class Server {

 public static void main(String[] args) throws Exception {
         
  ServerSocket ss= new ServerSocket(8888);
  while(true){
   Socket s = ss.accept();
   new Thread(new PicThread(s)).start();
  }
 }

}

class PicThread implements Runnable{
  
 private Socket s;
 public PicThread(Socket s ){
  this.s=s;
 }
 public void run() {
          int count=1;
         
        try {
   InputStream in= s.getInputStream();
   OutputStream out= s.getOutputStream();
   
   File f=  new File("G:"+s.getInetAddress().getHostAddress()+"("+(count++)+")"+".jpg");
   
   while(f.exists()){
     f=  new File("G:"+s.getInetAddress().getHostAddress()+"("+(count++)+")"+".jpg");
   }
   
   FileOutputStream fs= new FileOutputStream(f);
   byte[] buf= new byte[1024];
   int len ;
   while((len=in.read(buf))!=-1){
    fs.write(buf,0,len);
   }
   
   out.write("上传成功".getBytes());
   fs.close();
   in.close();
   out.close();
   s.close();
   
  } catch (Exception e) {
   e.printStackTrace();
   //throw new runtimeException();
   System.out.println("上传失败");
  }
         
 }
 
}
   

12 客服端通过键盘录入用户名
   服务端对这个用户名进行校验
 
  如果该用户存在,在服务端显示xxx, 已登录
  并在客户端显示 xxx ,该用户不存在

  最多就登录三次

13 自定义服务端,tomcat URL

   

   域名解析:
   1 想要将主机名翻译成IP地址,需要域名解析,DNS
   
   2 当我们访问主机的时候,先去本地主机的host找 在访问DNS 

14 图形界面的浏览器 :
package MyIE;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;
public class MyIE2 {

 public static void main(String[] args) {
                  
  MyIEGUI my = new MyIEGUI();
 }

}

class MyIEGUI extends Frame implements ActionListener{
    
  TextField tf= new TextField(40);
  TextArea ta= new TextArea(40,80);
  Panel p1 =new Panel();
  Panel p2= new Panel();
  Button b= new Button("RUN");
     public MyIEGUI(){
      this.setTitle("林枢的浏览器");
      this.setLocation(400, 200);
      this.setVisible(true);
      this.setSize(600,500);
      this.setResizable(false);
      ta.setEditable(false);
      ta.setBackground(Color.WHITE);
         p1.add(tf,BorderLayout.EAST);
         p1.add(b,BorderLayout.WEST);
         p2.add(ta,BorderLayout.CENTER);
         b.setSize(10,10);
         b.addActionListener(this);
        
         this.add(p1,BorderLayout.NORTH);
         this.add(p2,BorderLayout.CENTER);
      this.addWindowListener(new WindowAdapter(){
           
    public void windowClosing(WindowEvent e) {
     System.exit(0);
     System.out.println("bye bye");
    }
      });
     }
    
  public void actionPerformed(ActionEvent e) {
        
       String str=  tf.getText();
      
       // ta.append(str+"\n");
       try {
     URL urlpath =new URL(str);
     InputStream in= urlpath.openStream();
     
     BufferedReader br= new BufferedReader(new InputStreamReader(in));
     String line;
     while((line=br.readLine())!=null){
       ta.append(line+"\n");
     }
     
     
    } catch (MalformedURLException e1) {
     e1.printStackTrace();
    } catch (IOException e1) {
     e1.printStackTrace();
    }
       
  }
    
    
}

 

 

---------------------- android培训java培训、期待与您交流! ---------------------- 详细请查看:http://edu.csdn.net/heima

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值