Socket 网络通信

一、InerAddress 获取计算机信息

        try {
            //获取本机InerAddress实例
            InetAddress address =InetAddress.getLocalHost();
            address.getHostName(); //获取计算机名
            address.getHostAddress(); //获取计算机IP地址
            address.getAddress(); //获取数组形式的IP地址
            
            //其他方式获取InerAddress实例
            InetAddress address2 = InetAddress.getByName("主机名");
            InetAddress address3 = InetAddress.getByName("Ip地址");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

二、URL 网络资源的地址

        try {
            //创建URL实例
            URL url = new URL("http://www.baidu.com");
            //根据已存在的URL创建新的URL
            URL newUrl = new URL(url,"/index.html?username=tom");
            url.getProtocol(); //获取协议信息
            url.getHost(); //获取主机信息
            url.getPort(); //获取端口号
            url.getPath(); //获取文件路径
            url.getFile(); //获取文件名
            url.getRef(); //获取相对路径
            url.getQuery(); //获取查询字符串
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
          try {
                InputStream is =url.openStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String data = br.readLine();
                while(data!=null){
                    System.out.println(data);
                    data = br.readLine();
                }
                //释放资源
                is.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

三、ServerSocket 服务器端

        try {
            //1、创建服务器端Socket
            ServerSocket server = new ServerSocket(8888);
            //2、开始监听,等待客户端的连接
            Socket socket = server.accept();
            //3、获取输入流,读取客户端信息
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bf = new BufferedReader(isr);
            String info = null;
            while((info=bf.readLine())!=null){
                System.out.println("客户端请求:"+info);
            }
            //4、获取输出流,响应客户端请求
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write("服务器响应客户端");
            pw.flush();
            //5、释放资源
            server.close();
            socket.shutdownInput();
            is.close();
            isr.close();
            bf.close();
            os.close();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

四、Socket 客户端

        try {
            //1、创建客户端Socket,指定服务器地址和窗口
            Socket socket = new Socket("localhost",8888);
            //2、获取输出流,向服务器端发送信息
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write("客户端发送信息到服务器端");
            pw.flush();
            socket.shutdownOutput();
            //3、获取输入流,读取服务器端的响应信息
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String info = br.readLine();
            while(info!=null){
                System.out.println("服务器端相应:"+info);
            }
            //4、释放资源
            socket.close();
            os.close();
            pw.close();
            is.close();
            isr.close();
            br.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

五、多线程实现多客户端的通信

//服务器端的多线程类
public class ServerThread extends Thread {
    Socket socket = null;

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

    @Override
    public void run() {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader bf = null;
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            // 响应客户端的请求
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            bf = new BufferedReader(isr);
            String info = null;
            while ((info = bf.readLine()) != null) {
                System.out.println(info);
            }
            // 获取输出流,相应客户端请求
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            pw.write("服务器响应客户端");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { // 释放资源
            try {
                if (is != null)
                    is.close();
                if (isr != null)
                    isr.close();
                if (bf != null)
                    bf.close();
                if (os != null)
                    os.close();
                if (pw != null)
                    pw.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
            //修改服务器端的接收socket
            Socket socket = null;
            while(true){
                socket = server.accept();
                ServerThread thread = new ServerThread(socket);
                thread.start();

六、实现基于UDP的Socket通信

        //服务器端
        try {
            //1、创建服务器端,指定端口
            DatagramSocket socket = new DatagramSocket(8800);
            //2、创建数据报,用于接收客户端发送的数据
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            //3、接收客户端发送的数据
            socket.receive(packet);
            //4、读取数据
            String info =new String(data,0,packet.getLength());
            System.out.println("客户端信息:"+info);
            
            //1、创建数据报,用于接收服务器端响应的数据
            byte[] data1 = new byte[1024];
            DatagramPacket packet1 = new DatagramPacket(data1, data1.length);
            //2、接收服务器响应的数据
            socket.receive(packet1);
            //读取服务器端响应的数据
            String reply = new String(data1,0,packet1.getLength());
            System.out.println("服务器响应信息:"+reply);
            //4、释放资源
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //客户端
        try {
            //1、定义服务器端的地址、端口号、数据
            InetAddress address = InetAddress.getByName("localhost");
            int port = 8800;
            byte[] data ="客户端发送到服务器端的信息".getBytes();
            //2、创建数据报,包括发送的数据信息
            DatagramPacket packet = new DatagramPacket(data, data.length,address,port);
            //3、创建发送数据的对象
            DatagramSocket socket = new DatagramSocket();
            //4、向服务器端发送数据
            socket.send(packet);
            
            //1、定义客户端的地址、端口号、数据
            InetAddress address1 = packet.getAddress();
            int port1 = packet.getPort();
            byte[] data1 = "服务器端响应客户端的信息".getBytes();
            //2、创建数据报,包含响应的数据信息
            DatagramPacket packet1 = new DatagramPacket(data1, data1.length,address1,port1);
            //3、响应客户端
            socket.send(packet1);
            //4、释放资源
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

七、Socket常见问题

  • Socket 网络通信_第1张图片
  • Socket 网络通信_第2张图片
  • Socket 网络通信_第3张图片
  • Socket 网络通信_第4张图片

你可能感兴趣的:(Socket 网络通信)