黑马程序员---java基础----------------- 网络编程

网络模型:

    

网络通信三要素:IP地址、端口、传输协议。

网络通信原理:

      

IP地址:

    本地回环地址:127.0.0.1(可以测试网卡用,ping

     IPV4、IPV6(包含数字和字母)

    端口号的范围为0---65535之间,0----1023之间的端口数是用于一些知名的网络服务和应用 ,Web服务端口一般是80.

Socket:

    Socket就是为网络服务提供的一种机制。

    通信的两端都有Socket

    网络通信其实就是Socket间的通信。

    数据在两个Socket间通过IO传输。Socket在应用程序中创建,通过一种绑定机制与驱动程序建立关系,告诉自己所对应的IPPort

inetAddress:

import java.net.*;

class  IPDemo {  

    public static void main(String[] args) throws Exception  {   

        //InetAddress i = InetAddress.getLocalHost();     //InetAddress的静态方法,返回本地主机。可以获得InetAddress对象、

        //System.out.println(i.toString());

        //System.out.println("address:"+i.getHostAddress());

        //System.out.println("name:"+i.getHostName());

        InetAddress ia = InetAddress.getByName("thinkpad-sl400");   //将主机名作为参数传入可以获得InetAddress对象

        System.out.println("address:"+ia.getHostAddress());   //分别获得主机IP地址

        System.out.println("name:"+ia.getHostName());      //分别获得主机名称

    }

}

常见传输协议:TCP、UDP

UDP传输协议:

    将数据及源和目的封装成数据包,不需要建立连接

    每个数据包的大小都限制在64K以内

    因为无连接,是不可靠协议,可能会丢包。

    不需要建立连接,速度很快   

class  UdpSend {  

    public static void main(String[] args) throws Exception  {   

        DatagramSocket ds = new DatagramSocket(8888);        //1,创建udp服务。通过DatagramSocket对象。        

        //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);

        ds.send(dp);        //3,通过socket服务的send方法,将已有的数据包发送出去。。  

        ds.close();              //4,关闭资源。

    }

}

class  UdpRece {  

    public static void main(String[] args) throws Exception  {   

        DatagramSocket ds = new DatagramSocket(10000);     //1,创建udp socket,建立端点。  

        while(true)   {   

            byte[] buf = new byte[1024];   

            DatagramPacket dp = new DatagramPacket(buf,buf.length);      //2,定义数据包。用于存储数据

            ds.receive(dp);           //3,通过服务的receive方法将收到数据存入数据包中。 ------阻塞式方法。   

            String ip = dp.getAddress().getHostAddress();           //4,通过数据包的方法获取其中的数据。  

            String data = new String(dp.getData(),0,dp.getLength());

            int port = dp.getPort();

            System.out.println(ip+"::"+data+"::"+port);

        }

        ds.close();       //5,关闭资源  

    }

}

如何定义一个udp发送端:

  1,建立updsocket服务。

  2,提供数据,并将数据封装到数据包中。

  3,通过socket服务的发送功能,将数据包发出去。

  4,关闭资源。

如何定义udp的接收端:

  1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。  方便于明确哪些数据过来该应用程序可以处理。

  2,定义一个数据包,因为要存储接收到的字节数据。 因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。

  3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。

  4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。

  5,关闭资源。

....................................................................................................................

键盘录入向服务端发送数据

import java.net.*;

import java.io.*;

class  UdpSend2 {  

    public static void main(String[] args) throws Exception  {   

        DatagramSocket ds = new DatagramSocket();    //1,创建udp服务。通过DatagramSocket对象。  

        BufferedReader bufr =  new BufferedReader(new InputStreamReader(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 {  

    public static void main(String[] args) throws Exception  {   

        DatagramSocket ds = new DatagramSocket(10001);             //1,创建udp服务。通过DatagramSocket对象。 

        while(true)   {    

            byte[] buf = new byte[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);   

        }  

    }

}

.....................................................................................................................

编写一个聊天程序。 有收数据的部分,和发数据的部分。 这两部分需要同时执行。 那就需要用到多线程技术。 一个线程控制收,一个线程控制发。因为收和发动作是不一致的,

所以要定义两个run方法。 而且这两个方法要封装到不同的类中。

import java.io.*;

import java.net.*;

class Send implements Runnable {  

    private DatagramSocket ds;  

    public Send(DatagramSocket ds)  {   

        this.ds = ds;  

    }

    public void run()  {   

        try   {    

          BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

          String line = null;

          while((line=bufr.readLine())!=null)    {     

              byte[] buf = line.getBytes();

              DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);

              ds.send(dp);

              if("886".equals(line))      

                  break;    

          }   

        }   catch (Exception e)   {    

              throw new RuntimeException("发送端失败");   

        }  

    }

}

class Rece implements Runnable {

    private DatagramSocket ds;  

    public Rece(DatagramSocket ds)  {   

        this.ds = ds;  

    }  

    public void run()  {   

        try   {    

            while(true)    {     

                byte[] buf = new byte[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());

                if("886".equals(data))     {      

                    System.out.println(ip+"....离开聊天室");      

                    break;     

                }

                System.out.println(ip+":"+data);    

             }   

          }   catch (Exception e)   {    

              throw new RuntimeException("接收端失败");   

          }  

      }

}

class  ChatDemo {  

    public static void main(String[] args) throws Exception  {   

        DatagramSocket sendSocket = new DatagramSocket();   

        DatagramSocket receSocket = new DatagramSocket(10002);

        new Thread(new Send(sendSocket)).start();   

        new Thread(new Rece(receSocket)).start();

    }

}

 ................................................................................................................

TCP传输协议:1,tcp分客户端和服务端。    2,客户端对应的对象是Socket。服务端对应的对象是ServerSocket。

  建立连接,形成传输数据的通道

  在连接中进行大数据量传输

  通过三次握手完成连接,是可靠协议

  必须建立连接,所以小路会稍低

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

        后,在该通道进行数据的传输。

 

import java.io.*;

import java.net.*;

class  TcpClient {  

    public static void main(String[] args) throws Exception  {   

        Socket s = new Socket("192.168.1.254",10003);  //创建客户端的socket服务。指定目的主机和端口        

        OutputStream out = s.getOutputStream();       //为了发送数据,应该获取socket流中的输出流。

        out.write("tcp ge men lai le ".getBytes());

        s.close();  

    }

}

需求:定义端点接收数据并打印在控制台上。

    服务端: 1,建立服务端的socket服务。ServerSocket();  并监听一个端口。 2,获取连接过来的客户端对象。  通过ServerSokcet的 accept方法。没有连接就会等,

        所以这个方法阻塞式的。 3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,并获取到该客户端对象的读取流来读取发过来的数据。  并打印在控

        制台。4,关闭服务端。(可选)

class  TcpServer {  

    public static void main(String[] args) throws Exception  {   

        ServerSocket ss = new ServerSocket(10003);     //建立服务端socket服务。并监听一个端口。  

        while(true)   {   

            Socket s = ss.accept();       //通过accept方法获取连接过来的客户端对象。  

            String ip = s.getInetAddress().getHostAddress();   

            System.out.println(ip+".....connected");

            InputStream in = s.getInputStream();        //获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据。  

            byte[] buf = new byte[1024];   

            int len = in.read(buf);

            System.out.println(new String(buf,0,len));

            s.close();//关闭客户端.   

        }   

        //ss.close();  

    }

}

.............................................................................................................................

演示tcp的传输的客户端和服务端的互访。

需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息。

客户端:

    1,建立socket服务。指定要连接主机和端口。

    2,获取socket流中的输出流。将数据写到该流中。通过网络发送给服务端。

    3,获取socket流中的输入流,将服务端反馈的数据获取到,并打印。

    4,关闭客户端资源。

class TcpClient2 {  

    public static void main(String[] args)throws Exception  {   

        Socket s = new Socket("192.168.1.254",10004);      

        OutputStream out = s.getOutputStream();

        out.write("服务端,你好".getBytes());

        InputStream in = s.getInputStream();

        byte[] buf = new byte[1024];

        int len = in.read(buf);

        System.out.println(new String(buf,0,len));

        s.close();  

    }

}

class TcpServer2 {  

    public static void main(String[] args) throws Exception  {   

        ServerSocket ss = new ServerSocket(10004);

        Socket s = ss.accept();

        String ip = s.getInetAddress().getHostAddress();   

        System.out.println(ip+"....connected");   

        InputStream in = s.getInputStream();

        byte[] buf = new byte[1024];

        int len = in.read(buf);

        System.out.println(new String(buf,0,len));

        OutputStream out = s.getOutputStream();

        Thread.sleep(10000);   

        out.write("哥们收到,你也好".getBytes());

        s.close();

        ss.close();  

    }

}

..................................................................................................................................

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

 

分析:

    客户端: 既然是操作设备上的数据,那么就可以使用io技术,并按照io的操作规律来思考。

    源:键盘录入。

    目的:网络设备,网络输出流。 而且操作的是文本数据。可以选择字符流。同时提高效率,加入缓冲。

    步骤 :    1,建立服务。 2,获取键盘录入。 3,将数据发给服务端。 4,后去服务端返回的大写数据。 5,结束,关资源。

import java.io.*;

import java.net.*;

class  TransClient {  

    public static void 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);

        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));  //定义一个socket读取流,读取服务端返回大写  

        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读取流。
    目的:socket输出流。都是文本,装饰。

class  TransServer {  

    public static void main(String[] args) throws Exception  {   

        ServerSocket ss = new ServerSocket(10005);

        Socket s = ss.accept();   

        String ip = s.getInetAddress().getHostAddress();   

        System.out.println(ip+"....connected");

        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));          //读取socket读取流中的数据。  

        //目的。socket输出流。将大写数据写入到socket输出流,并发送给客户端。   

        //BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        PrintWriter out = new PrintWriter(s.getOutputStream(),true);

        String line = null;   

        while((line=bufIn.readLine())!=null)   {

            System.out.println(line);

            out.println(line.toUpperCase());

            //   bufOut.write(line.toUpperCase()); //   bufOut.newLine(); //   bufOut.flush();   

        }

        s.close();   

        ss.close();

    }

}

...........................................................................................

向服务器上传文件

import java.io.*;

import java.net.*;

class  TextClient {  

  public static void main(String[] args) throws Exception  {   

    Socket s = new Socket("192.168.1.254",10006);

    BufferedReader bufr = new BufferedReader(new FileReader("IPDemo.java"));

    PrintWriter out = new PrintWriter(s.getOutputStream(),true);

    String line = null;   

    while((line=bufr.readLine())!=null)   {    

        out.println(line);   

    }

    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 {  

  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()));

    PrintWriter out  = new PrintWriter(new FileWriter("server.txt"),true);

    String line = null;

    while((line=bufIn.readLine())!=null)   {    

      out.println(line);   

    }

    PrintWriter pw = new PrintWriter(s.getOutputStream(),true);   

    pw.println("上传成功");

    out.close();   

    s.close();   

    ss.close();

  }

}

 

posted @ 2013-06-04 19:54  zhao198627  阅读(215)  评论(0编辑  收藏  举报