Java基础-网络编程

  • B/S、C/S架构

B/S: 浏览器/服务器,基于浏览器程序,与服务器进行交互
C/S: 客户端/服务器,基于客户端程序,与服务器进行交互

  • Java写服务器程序

1.满足业务需求
2.处理高并发
3.大数据处理

  • 网络协议

语法:数据的结构
语义:描述请求、响应
同步:动作的实现顺序

  • TCP/IP协议

应用层
传输层
网际层
网络接口层

  • InetAddress常用方法
方法描述
public InetAddress getLocalHost()获取本机的 InetAddress 对象
public InetAddress getByName(String host)通过主机名创建 InetAddress 对象
public String getHostName()获取主机名称
public String getHostAddress()获取主机 IP 地址
public InetAddress getByAddress(byte[] addr)通过 IP 地址创建 InetAddress 对象
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);
        System.out.println(inetAddress.getHostName());
        System.out.println(inetAddress.getHostAddress());

        InetAddress inetAddress1 = inetAddress.getByName("localhost");
        System.out.println(inetAddress1);
  • URL常用方法
方法描述
public URL(String IP,String host,int port,String file)根据协议、IP地址、端口号、资源名称获取 URL 对象
public InputStream openStream()获取输入流对象
 public static void main(String[] args) {
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL("http","127.0.0.1",8080,"/login.html");
            inputStream = url.openStream();
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            String str = null;
            while ((str = bufferedReader.readLine())!=null){
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                reader.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • TCP协议

Java 通过 Socket 来完成 TCP 程序的开发,Socket 是一个类,使用该类可以在服务端与客户端之间建立可靠的连接。实际开发中,Socket 表示客户端,服务端使用 ServerSocket 来表示,ServerSocket 也是一个类,都是存放于 java.net 包中。
服务端创建 ServerSocket 对象,通过 accpet() 方法接收若干个表示客户端的 Socket 对象实现数据交互。

  • ServerSocket常用方法
方法描述
public ServerSocket(int port)根据端口创建 ServerSocket 对象
public ServerSocket(int port,InetAddress address)根据端口,InetAddress 创建 ServerSocket 对象
public int getSoTimeout()获取 SoTimeout
public InetAddress getInetAddress()获取服务器 IP 地址
public Socket accpet()等待客户端请求
  • Socket常用方法
方法描述
public Socket(String host,int port)根据主机、端口创建要连接的 Socket 对象
public Socket(InetAddress host,int port)根据 IP 地址、端口创建要连接的 Socket 对象
public Socket()创建没有连接的 Socket 对象
public InputStream getInputStream()返回 Socket 的输入流
public void close()关闭 Socket
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            serverSocket = new ServerSocket(8080);
            System.out.println("------服务端------");
            System.out.println("已启动,等待接收客户端请求...");
            boolean flag = true;
            while(flag){
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                dataInputStream = new DataInputStream(inputStream);
                String request = dataInputStream.readUTF();
                System.out.println("接收到了客户端请求:" + request);
                String response = "接收到了你的请求,OK";
                System.out.println("给客户端做出响应:" + response);
                outputStream = socket.getOutputStream();
                dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeUTF(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataInputStream.close();
                inputStream.close();
                socket.close();
                serverSocket.close();
                dataOutputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        try {
            socket = new Socket("127.0.0.1", 8080);
            System.out.println("------客户端------");
            String request = "Hello";
            System.out.println("客户端说:" + request);
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(request);
            inputStream = socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            String response = dataInputStream.readUTF();
            System.out.println("服务端响应为:" + response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
                outputStream.close();
                socket.close();
                dataInputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • DatagramSocket常用方法
方法描述
public DatagramSocket(int port)创建对象
public void send(DatagramPacket p)发送数据包
public void receive(DatagramPacket p)接收数据包
  • DatagramPacket常用方法
方法描述
public DatagramPacket(byte buf[],int length,InetAddress address,int port)创建数据包
public byte[] getData()获取数据
public int getLength()获取数据长度
public int getPort()获取发送数据包的端口
public SocketAddress getSocketAddress()获取发送数据的Socket信息
public class TerminalA {
    public static void main(String[] args) {
        try {
            //接收数据
            byte[] buff = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(buff, buff.length);
            DatagramSocket datagramSocket = new DatagramSocket(8181);
            datagramSocket.receive(datagramPacket);
            String message = new String(datagramPacket.getData(),0,datagramPacket.getLength());
            System.out.println("我是TerminalA,接收到了"
                    + datagramPacket.getSocketAddress().toString() +
                    ":" + datagramPacket.getPort() + "传来的数据:" + message);
            //发送数据
            String response = "我是TerminalA,已接收到你发来的数据。";
            SocketAddress socketAddress = datagramPacket.getSocketAddress();
            DatagramPacket datagramPacket2 = new DatagramPacket(
                    response.getBytes(),
                    response.getBytes().length,
                    socketAddress);
            datagramSocket.send(datagramPacket2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class TerminalB {
    public static void main(String[] args) {
        try {
            //发送消息
            String message = "我是TerminalB,你好!";
            InetAddress inetAddress = InetAddress.getByName("localhost");
            DatagramPacket datagramPacket = new DatagramPacket(
                    message.getBytes(),
                    message.getBytes().length,
                    inetAddress,
                    8181);
            DatagramSocket datagramSocket = new DatagramSocket(8080);
            datagramSocket.send(datagramPacket);
            //接收消息
            byte[] buff = new byte[1024];
            DatagramPacket datagramPacket2 = new DatagramPacket(buff, buff.length);
            datagramSocket.receive(datagramPacket2);
            String response = new String(datagramPacket2.getData(),0,datagramPacket2.getLength());
            System.out.println("我是TerminalB,接收到了" + datagramPacket2.getSocketAddress().toString() + ":" +
                    datagramPacket2.getPort() + "返回的数据:" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 多线程下的TCP
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080);
            System.out.println("服务器已启动");
            while (true){
                Socket socket = serverSocket.accept();
                new Thread(new ServerRunnable(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ServerRunnable implements Runnable {

    private Socket socket;

    public ServerRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        try {
            inputStream = this.socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            String request = dataInputStream.readUTF();
            System.out.println(request);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                dataInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Client {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(new ClientRunnable(i)).start();
        }
    }
}
public class ClientRunnable implements Runnable {
    private int num;
    public ClientRunnable(int num) {
        this.num = num;
    }
    @Override
    public void run() {
        Socket socket = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            socket = new Socket("localhost", 8080);
            String message = "我是客户端"+this.num;
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值