Java 网络编程

TCP/IP
TCP/IP详解
这里写图片描述
这里写图片描述
TCP传递的数据
这里写图片描述

这里写图片描述

TCP的交互数据流
这里写图片描述
TCP成块数据流
这里写图片描述

TCP Demo

    /**
     * 服务器
     */
    public static void test4() {
        ServerSocket ss = null;
        Socket socket = null;
        ExecutorService es = Executors.newCachedThreadPool();
        try {
            ss = new ServerSocket(10000);
            System.out.println("服务器已启动:");
            while (true) {
                // 获得链接
                socket = ss.accept();
                // 指定线程处理
                es.submit(new LogicThread(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ss != null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 客户端
     */
    public static void test2() {
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        //服务器端IP地址
        String serverIP = "127.0.0.1";
        //服务器端端口号
        int port = 10000;
        //发送内容
        String data = "Hello";
        try {
            //建立连接
            socket = new Socket(serverIP, port);
            //发送数据
            os = socket.getOutputStream();
            os.write(data.getBytes());
            //接收数据
            is = socket.getInputStream();
            byte[] b = new byte[1024];
            int n;
            n = is.read(b);
            //输出反馈数据
            System.out.println("服务器反馈:" + new String(b, 0, n));

        } catch (Exception e) {
            e.printStackTrace(); //打印异常信息
        } finally {
            try {
                //关闭流和连接
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 连接处理线程
 */
public class LogicThread extends Thread {
    Socket socket;
    InputStream is = null;
    OutputStream os = null;

    public LogicThread(Socket socket) {
        this.socket = socket;
        start();
    }

    @Override
    public void run() {
        byte[] b = new byte[8 * 1024];

        try {
            is = socket.getInputStream();
            os = socket.getOutputStream();
            int n = 0;
            while ((n = is.read(b)) != -1){
                //逻辑处理
                byte[] response = logic(b, 0, n);
                //反馈数据
                os.write(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    private void close() {
        try {
            //关闭流和连接
            if (socket != null)
                socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private byte[] logic(byte[] b, int off, int len) {
        String s = "收到了:" + new String(b, off, len);
        System.out.println(s);
        return s.getBytes();
    }
}

UDP

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Properties;

public class MyChart {

    public void run() throws IOException {
        // 读取配置文件
        Properties prop = new Properties();
        // 加载数据
        prop.load(new FileInputStream("chart.ini"));
        // 目标IP
        String ip = prop.getProperty("ip");
        // 目标端口:
        String port_str = prop.getProperty("port");
        int port = Integer.parseInt(port_str);
        // 自己的端口
        String my_port_str = prop.getProperty("my_port");
        int my_port = Integer.parseInt(my_port_str);
        DatagramSocket ds = new DatagramSocket(my_port);

        new Thread(new SendServer(ds, port, ip)).start();
        new Thread(new ReceiveTask(ds)).start();
    }

    // log
    private Print print = new Print();
    // log
    private In in = new In();

    /**
     * 发送端服务器
     */
    class SendServer implements Runnable {
        private DatagramSocket ds;
        private int port;
        private String ip;

        public SendServer(DatagramSocket ds, int port, String ip) {
            this.ds = ds;
            this.port = port;
            this.ip = ip;
        }

        @Override
        public void run() {
            try {
                String data;
                while ((data = in.in()) != null) {
                    byte[] buff = data.getBytes();
                    DatagramPacket p = new DatagramPacket(buff, buff.length, InetAddress.getByName(ip), port);
                    ds.send(p);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 接收端服务器
     */
    class ReceiveTask implements Runnable {

        /**
         * 套接字对象
         */
        public DatagramSocket ds;

        public ReceiveTask(DatagramSocket ds) {
            this.ds = ds;
        }

        @Override
        public void run() {
            while (true) {
                DatagramPacket p = new DatagramPacket(new byte[1024], 1024);
                try {
                    ds.receive(p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String ip = p.getAddress().getHostAddress();
                int port = p.getPort();
                String s = new StringBuilder().append("[").append(ip).append(":").append(port)
                        .append("]").append(new String(p.getData(), 0, p.getLength())).toString();
                print.print(s);
            }
        }
    }

    /**
     * 输出到平台
     */
    class Print {
        void print(String s) {
            System.out.println(s);
        }
    }

    /**
     * 输入
     */
    class In {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String in() throws IOException {
            return br.readLine();
        }
    }
}

URL

    public static void test1(String outpath) {
        URI uri = null;
        try {
            //建议的用法是使用 URI 指定资源,然后在访问资源时将其转换为 URL。从该 URL 可以获取 URLConnection 以进行良好控制,也可以直接获取 InputStream。
            uri = new URI("http://www.baidu.com/");
            URL url = uri.toURL();
            InputStream in = url.openStream();
            Reader reader = new InputStreamReader(in);
            BufferedReader lr = new BufferedReader(reader);
            String d = lr.readLine();
            System.out.println(d);
            d = lr.readLine();
            System.out.println(d);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

网络编程的东西太多,日后再详细补充
网络编程,还涉及并发,线程的处理等等。
可以研究研究 netty
http://netty.io/
https://github.com/netty/netty
java网络编程详解
什么是套接字(socket)
它是网络通信过程中端点的抽象表示,包含进行网络通信必需的五种信息:

  1. 连接使用的协议
  2. 本地主机的IP地址
  3. 本地进程的协议端口
  4. 远地主机的IP地址
  5. 远地进程的协议端口。
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值