JAVA网络编程 学习

《JAVA核心技术 卷二》 网络章节

使用Java进行网络编程时,由虚拟机实现了底层复杂的网络协议,Java程序只需要调用Java标准库提供的接口,就可以简单高效地编写网络程序。

  1. 网络基本概念:
    ip地址 = 因特网地址:指用一串数字表示的主机地址
    主机地址:
    端口号:
    套接字(socket):网络软件中的一个抽象概念 ,负责能使该程序内部和外部通信。

  1. 编写网络客户端连接到服务器:

a.连接到某个端口,输出其收到的信息。

public class SocketTest {
    public static void main(String[] args){
        try{
            //构建连接socket 参数:host + port
            //Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            //构建无连接socket,防止构建有连接的socket时超时,而没有设超时时间
            Socket s = new Socket();
            //连接超时10s
            try {
                s.connect(new InetSocketAddress("java.sun.com", 80), 10000);
                InputStream inSteam = s.getInputStream();
                Scanner in = new Scanner(inSteam);
                while (in.hasNextLine()) {
                    String line = in.nextLine();
                    System.out.println(line);
                }
            }
            finally {
                s.close();
            }
        } catch (SocketTimeoutException er){
            er.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

b.使用InetAddress类实现主机地址和因特网地址的转换

public class InetAddressTest {
    public static void main(String[] args){
        try{
            //translate hostname to InetAddress
            InetAddress[] addresses = InetAddress.getAllByName("java.sun.com");
            for (InetAddress a : addresses){
                System.out.println(a);
            }
            //获取本地因特网地址
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

a. 实现单线程服务器

public class MyServer {
    public static void main(String[] args){
        try{
            // build a server by port
            ServerSocket s = new ServerSocket(8189);
            System.out.println("open server");
            // wait for client connect
            try (Socket incoming = s.accept()) {
                InputStream inputStream = incoming.getInputStream();
                OutputStream outputStream = incoming.getOutputStream();
                // 扫描器
                Scanner in = new Scanner(inputStream);
                // 写入器
                PrintWriter out = new PrintWriter(outputStream, true);
                // 输出信息
                out.println("Hello, key Bye out");

                boolean done = false;
                while (!done && in.hasNextLine()) {
                    // 接收信息
                    String line = in.nextLine();
                    out.println("haha," + line);
                    if (line.trim().equals("Bye"))
                        done = true;
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

b. 访问单线程服务器

public class SocketTest {
    public static void main(String[] args){
        try{
            //构建连接socket 参数:host + port
            //Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            //构建无连接socket,防止构建有连接的socket时超时,而没有设超时时间
            //连接超时10s
            try (Socket s = new Socket()) {
                s.connect(new InetSocketAddress("localhost", 8189), 10000);
                InputStream inSteam = s.getInputStream();
                OutputStream outSteam = s.getOutputStream();
                Scanner in = new Scanner(inSteam);
                PrintWriter out = new PrintWriter(outSteam, true);
                while (in.hasNextLine()) {
                    String line = in.nextLine();
                    System.out.println(line);
                    Scanner sysIn = new Scanner(System.in);
                    out.println(sysIn.next());
                }
            }
        } catch (SocketTimeoutException er){
            er.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

c. 实现多线程服务器

public class MyMultiSever {
    public static void main(String[] args) {
        try{
            ServerSocket s = new ServerSocket(8189);
            System.out.println("open server");
            while(true){
                Socket incoming = s.accept();
                Runnable r = new ThreadHandled(incoming);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

class ThreadHandled implements Runnable{
    Socket incoming;
    ThreadHandled(Socket socket){
        incoming = socket;
    }
    public void run(){
        try{
            InputStream inputStream = incoming.getInputStream();
            OutputStream outputStream = incoming.getOutputStream();
            // 扫描器
            Scanner in = new Scanner(inputStream);
            // 写入器
            PrintWriter out = new PrintWriter(outputStream, true);
            // 输出信息
            out.println("Hello, key Bye out");
            boolean done = false;
            while (!done && in.hasNextLine()) {
                // 接收信息
                String line = in.nextLine();
                out.println("haha," + line);
                if (line.trim().equals("Bye"))
                    done = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

d. 半关闭能力:允许设置shutdownOutput() 或者 shutdownInput() 将输出流或输入流关闭,达到只输入或只输出效果。

e. 可中断套接字
对于套接字链接或者传输数据时,线程可能因套字节无法响应而阻塞,无法通过调用interrupt来解除阻塞,通过SocketChannel处理。


  1. 发送E-mail

  1. URL连接(WEB服务)
    a. URL和URI:URL 统一资源定位符(uniform resource locator),URI 统一资源标识符(uniform resource identifier)。URI是个纯粹的语法结构,用于指定标识Web资源的字符串的各个部分;URL是URI的一个特例,用于定位Web资源。在java类库中,URI不包含访问资源的方法,唯一作用是解析;URL类可以打开一个到达资源的流。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值