java高级_03

一 网络
1 网络:信息传输的平台(数据共享)
2 协议:通信的约定
3 分层:OSI/IOS标准:七层
        TCP/IP     : 五层
二 通信地址
1 网络地址InetAddress:ip/主机名
2 端口port           :标识某一个通信程序
3 Socket地址         :ip + port

4 URL
  统一资源定位符:通过URL可以获取网络上的数据
  Get/Post

三 两种Socket传输协议
1 TCP
有链接 可靠的字节流网络通信

1.1 服务端
    1.1.1 创建ServerSocket(指定端口号)
    1.1.2 服务端被动等待客户端的连接
        accept()
    1.1.3 通过连接好的客户端的socket的字节流进行通信
        getInputStream
        getOutputStream
    1.1.4 通信完成关闭流和Socket

1.2 客户端
    1.2.1 创建Socket(指定连接哪一个服务端(ip+port))
          客户端主动发起连接
    1.2.2 通过socket的字节流进行通信
    1.2.3 通信完成关闭流和Socket


2 UDP
  无连接 不可靠 数据报格式的网络通信
  2.1 接收数据
      2.1.1 准备DatagramSocket,指定端口号
      2.1.2 可以接收数据
            准备接收数据的DatagramPacket
            receive(DatagramPacket p)
      2.1.3 关闭socket
            close

  2.2 发送数据
      2.1.1 准备DatagramSocket,指定端口号
      2.1.2 可以发送数据
            准备发送数据的DatagramPacket(指定发送目的地的ip+port)
            send(DatagramPacket p)
      2.1.3 关闭socket
            close


四 非阻塞的异步通信方式
1 通道+选择器

2 服务端
  2.1 服务端的套接字通道
      ServerScoketChannel.open();
  2.2 绑定服务端的端口
      ServerScoketChannel.socket().bind(new InetScoketAddress(port));
  2.3 设置服务端为非阻塞方式
       ServerScoketChannel.configureBlocking(false);
  2.4 把服务端通道的accept事件注册到一个选择器
      2.4.1 打开一个选择器
            Selector.open();
      2.4.2 注册
             ServerScoketChannel.register(selector,SelectionKey.OP_ACCEPT);
 
 2.5 从选择器中获取通道的事件并处理
     while(true)
     {
    Selector.select(10000);//从选择器中选择事件
        
    //没有超时,代表选择器中有事件
        Set<> set = Selector.selectedKeys();//取出选择器中当前的所有事件
    循环遍历这个集合,处理所有的事件
        遍历时,对不同的事件要做不同的处理

     }

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class TestHttp {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //httpGet();
        httpPost();
    }
    
    //GET(查询请求直接提交)
    private static void httpGet()
    {
        try {
            URL url = new URL("http://www.baidu.com/s?wd=java");
            HttpURLConnection hc = (HttpURLConnection)url.openConnection();//打开连接
            hc.connect();//连接
            BufferedReader br = new BufferedReader(new InputStreamReader(hc.getInputStream(),"UTF-8"));
            String string = null;//保存每一行
            while((string = br.readLine()) != null)
            {
                System.out.println(string);
            }
            
            br.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    //POST
    private static void httpPost()
    {
        try {
            URL url = new URL("http://www.haosou.com/s");
            HttpURLConnection hc = (HttpURLConnection)url.openConnection();//打开连接
            
            
            hc.setDoOutput(true);//把输出流打开
            hc.setRequestMethod("POST");//设置为POST方式
            hc.setUseCaches(false);//POST方式不用缓存
            hc.setRequestProperty("Content-type", "application/x-java-serialized-object");
            
            hc.connect();//连接
            //获取输出流,包装为打印流
            PrintWriter pw = new PrintWriter(hc.getOutputStream());
            pw.print("q=java");
            pw.close();
            
            BufferedReader br = new BufferedReader(new InputStreamReader(hc.getInputStream(),"UTF-8"));
            String string = null;//保存每一行
            while((string = br.readLine()) != null)
            {
                System.out.println(string);
            }
            
            br.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}


DatagramSocketTest

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;


public class Receive {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        DatagramSocket socket = new DatagramSocket(8084);
        Scanner in = new Scanner(System.in);
        while(true){
            
            byte[] bytes = new byte[100];
            DatagramPacket rdata = new DatagramPacket(bytes, 100);
            
            System.out.println("等待接受数据:");
            socket.receive(rdata);
            System.out.println(rdata.getAddress() + "," + rdata.getPort() + ":" + new String(bytes));
            
            if((new String(bytes,0,rdata.getLength())).equals("Q")){
                break;
            }
            
            System.out.println("要发送的消息:");
            String str = in.next();
            DatagramPacket sdata = new DatagramPacket(str.getBytes(), str.getBytes().length,rdata.getAddress(),rdata.getPort());
            socket.send(sdata);
        }
        socket.close();

    }

}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;


public class Send {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        DatagramSocket socket = new DatagramSocket(8083);
        Scanner in = new Scanner(System.in);
        while(true){
            System.out.println("要发送的消息:");
            String str = in.next();
            byte [] bytes =str.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length,InetAddress.getLocalHost(),8084); 
            socket.send(datagramPacket);
            if(str.equals("Q")){
                break;
            }
            
            byte [] bytes1 = new byte[100];
            DatagramPacket rdata = new DatagramPacket(bytes1, 100);
            socket.receive(rdata);
            System.out.println(rdata.getAddress()+","+rdata.getPort()+":"+new String(bytes1));
        }
        socket.close();

    }

}

Socket

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class Client {
    /*
     * @fun 客户端
     * @author Fly-Tomato
     * 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        // TODO Auto-generated method stub
        Socket socket = new Socket("127.0.0.1",8082);
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        while(true){
            System.out.println("要发送:");
            String str =in.nextLine();
            printWriter.println(str);
            printWriter.flush();
            
            System.out.println(bufferedReader.readLine());
            if(str.equals("Q")){
                break;
            }
        }
        System.out.println("通信结束!");
        printWriter.close();
        socket.close();

    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/*
 * @fun 多线程
 * @author Fly-Tomato
 * 
 */

public class Echo implements Runnable {
    
    private Socket socket;
    public Echo(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            InputStreamReader is = new InputStreamReader(socket.getInputStream());
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
            BufferedReader bs = new BufferedReader(is);
            while(true){
                System.out.println("等待读数据客户端发的数据...");
                String str = bs.readLine();
                System.out.println(socket.getPort()+"发送了:"+str);
                printWriter.println("ECHO:"+str);
                printWriter.flush();
                if(str.equals("Q")){
                    break;
                }
            }
            bs.close();
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("网络异常");
        }
        
    }

}

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    /*
     * @fun 服务端
     * @author Fly-Tomato
     * 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ServerSocket serverSocket = new ServerSocket(8082);
        int i = 10;
        while((i--) > 0){
            System.out.println("服务器已启动,等待连接中.....");
            Socket socket = serverSocket.accept();
            System.out.println(socket.getPort()+"已连接到主机");
            Thread thread = new Thread(new Echo(socket));
            thread.start();
        }
        serverSocket.close();
        System.out.println("通信结束");
        

    }

}

ServerSocketChannel

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class Server {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8085));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select(5000) == 0) {
                System.out.print("*");
                continue;
            }

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                if (key.isAcceptable()) {
                    SocketChannel client = ((ServerSocketChannel) key.channel())
                            .accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ,
                            ByteBuffer.allocate(100));
                }
                if (key.isReadable()) {
                    SocketChannel client = ((SocketChannel) key.channel());
                    ByteBuffer bytes = (ByteBuffer) key.attachment();
                    bytes.clear();
                    client.read(bytes);
                    bytes.flip();
                    System.out.println(Charset.forName("UTF-8").newDecoder().decode(bytes).toString());

                }
            }
            keys.clear();

        }

    }

}

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) throws UnknownHostException,
            IOException {
        Socket socket = new Socket("127.0.0.1", 8085);
        // 2 通信
        // 输出流负责发送数据
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("发送:");
            String dataString = scanner.nextLine();

            printWriter.println(dataString);// 发送数据
            printWriter.flush();// 清缓冲区

            if (dataString.equals("Q")) {
                break;
            }
        }

        System.out.println("发送完毕");

        printWriter.close();

        socket.close();
    }

}


你可能感兴趣的:(java高级_03)