javaSE-网络编程

概述

java中的网络编程大致分为两类,分别为TCP与UDP,至于两者的区别,可以去查看计算机网络相关的知识。
无论是TCP还是UDP,都需要知道双方的IP地址,才能互相发送数据。而发送数据是通过java中的字节流来进行传递的,所以在java的网络编程中,java的IO流是十分重要的。

TCP编程

TCP实现简单的聊天功能

  1. 服务器端的创建
    在java的TCP编程中,服务器端是通过创建ServerSocket类的实例对象来创建的,然后调用该对象的accept方法来阻塞监听客户端的链接,一旦接收到客户端的连接,该方法就会返回一个Socket对象实例,服务器端接收客户端的消息与返回客户端消息都是通过这个Socket对象来进行的。
  2. 客户端的创建
    客户端只需要创建一个Socket对象,给它设置好服务器端的IP,端口等属性后调用connect方法进行连接即可,如果连接失败会抛出IO异常。连接成功后就通过这个Socket对象进行与服务器端数据的传递。
  3. 客户端与服务器端创建完成后,先运行服务器端,然后再运行客户端。
  4. 下面是一个简单的实现。需要注意的是,当连接创建成功后,服务器端与客户端都会有一个Socket对象,这两个对象就像是镜像一样,完全是相反的,一方的输入流就是对方的输出流,一方的输出流就是对方的输入流。除此之外,当传递完数据后一定要记得调用shutdownXXX方法,私下可以将下面的demo中的shutdownXXX方法注释掉试试看会发什么,为什么会出现这种情况。
    demo示例,服务器端:
/**
 * @Classname DemoServer1
 * @Date 2020/11/21 18:19
 * @author hzq
 */
package com.hzq.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class DemoServer1 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            //创建一个服务器并绑定端口号8000
            serverSocket = new ServerSocket(8000);
            //等待客户端的连接
            socket = serverSocket.accept();
            //获取客户端的输出流,也就是服务器端的输入流
            is = socket.getInputStream();
            //获取客户端输入流,也就是服务器端输出流
            os = socket.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            String s = "";
            //接收客户端发来的数据
            while ((len=is.read(bytes))!=-1){
                s += new String(bytes,0,len,StandardCharsets.UTF_8);
            }
            //打印客户端发送的数据
            System.out.println(s);
            os.write("你好!".getBytes(StandardCharsets.UTF_8));
            socket.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (serverSocket != null){
                serverSocket.close();
            }
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }
}

demo示例,客户端:

/**
 * @Classname DemoClient1
 * @Date 2020/11/21 18:19
 * @author hzq
 */
package com.hzq.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;

public class DemoClient1 {

    public static void main(String[] args) throws IOException {
        Socket socket = null;
        InputStream is = null;
        OutputStream os =null;
        //获取本机ip地址
        InetAddress inetAddress = InetAddress.getByName("localhost");
        try {
            //创建空socket
            socket = new Socket();
            //连接服务器
            socket.connect(new InetSocketAddress(inetAddress,8000),8000);
            //获取服务器端输入流,也就是客户端输出流
            os = socket.getOutputStream();
            //向服务器发送消息
            os.write("你好啊!".getBytes(StandardCharsets.UTF_8));
            //关闭客户端输出流
            socket.shutdownOutput();
            is = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            String s = "";
            //接收服务器发来的数据
            while ((len=is.read(bytes))!=-1){
                s += new String(bytes,0,len,StandardCharsets.UTF_8);
            }
            //打印服务器发送的数据
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }
}

TCP实现文件的上传与下载

demo示例,服务器

/**
 * @Classname DemoServer1
 * @Date 2020/11/21 18:19
 * @author hzq
 */
package com.hzq.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DemoServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            //创建一个服务器并绑定端口号8000
            serverSocket = new ServerSocket(8000);
            //等待客户端的连接
            socket = serverSocket.accept();
            //获取客户端的输出流,也就是服务器端的输入流
            is = socket.getInputStream();
            int i = is.read();
            if (i == 1){
                os = new FileOutputStream(new File("up.jpg"));
                byte[] bytes = new byte[1024];
                int len = 0;
                //接收客户端发来的数据
                while ((len=is.read(bytes))!=-1){
                    os.write(bytes,0,len);
                }
                socket.shutdownInput();
            }
            if (i == 2){
                os = socket.getOutputStream();
                Class<?> c1 = Class.forName("com.hzq.tcp.DemoClient2");
                URL resource = c1.getResource("./demo.jpg");
                is = new FileInputStream(new File(resource.toURI()));
                byte[] bytes = new byte[1024];
                int len = 0;
                //接收客户端发来的数据
                while ((len=is.read(bytes))!=-1){
                    os.write(bytes,0,len);
                }
                socket.shutdownOutput();
            }
        } catch (IOException | URISyntaxException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (serverSocket != null){
                serverSocket.close();
            }
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }
}

demo示例,客户端:

/**
 * @Classname DemoClient1
 * @Date 2020/11/21 18:19
 * @author hzq
 */
package com.hzq.tcp;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class DemoClient2 {

    public static void main(String[] args) throws IOException {
//        upLoad();
        downLoad();
    }
    public static void upLoad() throws IOException{
        Socket socket = null;
        InputStream is = null;
        OutputStream os =null;
        //获取本机ip地址
        InetAddress inetAddress = InetAddress.getByName("localhost");
        try {
            //创建空socket
            socket = new Socket();
            //连接服务器
            socket.connect(new InetSocketAddress(inetAddress,8000),8000);
            //获取服务器端输入流,也就是客户端输出流
            os = socket.getOutputStream();
            //获取文件流
            Class<?> c1 = Class.forName("com.hzq.tcp.DemoClient2");
            URL resource = c1.getResource("./demo.jpg");
            is = new FileInputStream(new File(resource.toURI()));
            byte[] sendData = new byte[1];
            sendData[0] = 1;
            os.write(sendData);
            byte[] bytes = new byte[1024];
            int len = 0;
            //接收服务器发来的数据
            while ((len=is.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
            //关闭客户端输出流
            socket.shutdownOutput();
        } catch (IOException | ClassNotFoundException | URISyntaxException e) {
            e.printStackTrace();
        }finally {
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }
    public static void downLoad() throws IOException{
        Socket socket = null;
        InputStream is = null;
        OutputStream os =null;
        //获取本机ip地址
        InetAddress inetAddress = InetAddress.getByName("localhost");
        try {
            //创建空socket
            socket = new Socket();
            //连接服务器
            socket.connect(new InetSocketAddress(inetAddress,8000),8000);
            //获取服务器端输入流,也就是客户端输出流
            os = socket.getOutputStream();
            //向服务器发送消息
            byte[] sendData = new byte[1];
            sendData[0] = 2;
            os.write(sendData);
            //关闭客户端输出流
            socket.shutdownOutput();
            is = socket.getInputStream();
            os = new FileOutputStream(new File("down.jpg"));
            byte[] bytes = new byte[1024];
            int len = 0;
            //接收服务器发来的数据
            while ((len=is.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }
}

UDP编程

UDP实现简单的聊天

  1. 先创建接收端,创建一个DatagramSocket对象,并绑定一个端口号,然后创建一个DatagramPacket对象,socket对象调用receive方法阻塞接收数据。
  2. 创建发放段端,同接收端相似,只不过发送端是将数据封装到packet对象中后,受用socket对象的send方法将packet对象发送出去。
    demo示例,接收端:
/**
 * @Classname DemoServer1
 * @Date 2020/11/21 21:07
 * @author hzq
 */
package com.hzq.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class DemoClient2 {
    public static void main(String[] args) throws IOException {
        //创建socket并绑定端口号
        DatagramSocket socket = new DatagramSocket(8000);
        byte[] bytes = new byte[1024];
        //创建数据包
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        //阻塞接收数据
        socket.receive(packet);
        byte[] data = packet.getData();
        System.out.println(new String(data, StandardCharsets.UTF_8));
        InetAddress inetAddress = packet.getAddress();
        int port = packet.getPort();
        byte[] bytes1 = "你也好".getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet1 = new DatagramPacket(bytes1,0,bytes1.length,inetAddress,port);
        socket.send(packet1);
        socket.close();
    }
}

demo示例,发送端:

/**
 * @Classname DemoClient1
 * @Date 2020/11/21 21:07
 * @author hzq
 */
package com.hzq.udp;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class DemoClient1 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8001);
        byte[] bytes = "你好世界!".getBytes(StandardCharsets.UTF_8);
        InetAddress inetAddress = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, inetAddress, 8000);
        socket.send(packet);
        byte[] bytes1 = new byte[1024];
        DatagramPacket packet1 = new DatagramPacket(bytes1, 0, bytes.length);
        socket.receive(packet1);
        byte[] data = packet1.getData();
        System.out.println(new String(data,StandardCharsets.UTF_8));
        socket.close();
    }
}

结束语

这样,java的网络编程的基础算是完成了,有时间写一个GUI的聊天室。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值