Java网络套接字Socket编程

Socket概述

Socket,译作网络套接字,是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。网络套接字与一个应用进程(ip和端口号)绑定。

Socket与ServerSocket

Socket与ServerSocket是Java中Socket编程的常用类,一般分别指客户端和服务端的socket。

工作流程:

  • 服务端bind():绑定端口
  • 服务端accept():等待客户端建立连接
  • 客户端connect():连接到服务端
  • 双方进行IO操作
  • 服务端和客户端close():关闭socket连接

代码示例

实现一个客户端给服务端发送数据,服务端按原数据返回的程序。

第一版

服务端:

public class Server {
    public static void main(String[] args) {
        final int DEFAULT_PORT = 8888;
        ServerSocket serverSocket = null;

        // 绑定监听端口
        try {
            serverSocket = new ServerSocket(DEFAULT_PORT);
            System.out.println("启动服务器,监听端口"+DEFAULT_PORT);
            while (true){
                Socket socket = serverSocket.accept();//等待客户端连接,阻塞
                System.out.println("客户端["+socket.getPort()+"]已连接");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream())
                );
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                );
                // 读取客户端发送的消息
                String msg = reader.readLine();
                if(msg!=null){
                    System.out.println("客户端["+socket.getPort()+"]: " + msg);
                    //回复客户发送的消息
                    writer.write("服务器: "+msg+"\n");
                    writer.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客户端:(运行于同一台主机上)

public class Client {
    public static void main(String[] args) {
        final String DEFAULT_SERVER_HOST="127.0.0.1";
        final int DEFAULT_PORT = 8888;
        Socket socket = null;
        BufferedWriter writer = null;

        try {
            //创建socket
            socket = new Socket(DEFAULT_SERVER_HOST,DEFAULT_PORT);

            //创建IO流
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );
            writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );

            // 等待用户输入信息
            BufferedReader consoleReader = new BufferedReader(
                    new InputStreamReader(System.in)
            );
            String input = consoleReader.readLine();

            //发送消息给服务器
            writer.write(input+"\n");
            writer.flush();

            //读取服务器返回的消息
            String msg = reader.readLine();
            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

第二版

一个客户端可以反复发送消息,直到输入quit退出

客户端:

public class Client {
    public static void main(String[] args) {
        final String QUIT = "quit";
        final String DEFAULT_SERVER_HOST="127.0.0.1";
        final int DEFAULT_PORT = 8888;
        Socket socket = null;
        BufferedWriter writer = null;

        try {
            //创建socket
            socket = new Socket(DEFAULT_SERVER_HOST,DEFAULT_PORT);

            //创建IO流
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );
            writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );

            // 等待用户输入信息
            BufferedReader consoleReader = new BufferedReader(
                    new InputStreamReader(System.in)
            );
            while(true){
                String input = consoleReader.readLine();
                if(input.equals(QUIT)) break;
                //发送消息给服务器
                writer.write(input+"\n");
                writer.flush();

                //读取服务器返回的消息
                String msg = reader.readLine();
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务端:

public class Server {
    public static void main(String[] args) {
        final int DEFAULT_PORT = 8888;
        ServerSocket serverSocket = null;

        // 绑定监听端口
        try {
            serverSocket = new ServerSocket(DEFAULT_PORT);
            System.out.println("启动服务器,监听端口"+DEFAULT_PORT);
            while (true){
                Socket socket = serverSocket.accept();//等待客户端连接,阻塞
                System.out.println("客户端["+socket.getPort()+"]已连接");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream())
                );
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                );

                String msg = null;
                while((msg = reader.readLine())!=null){
                    // 读取客户端发送的消息
                    System.out.println("客户端["+socket.getPort()+"]: " + msg);
                    //回复客户发送的消息
                    writer.write("服务器: "+msg+"\n");
                    writer.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/java%e7%bd%91%e7%bb%9c%e5%a5%97%e6%8e%a5%e5%ad%97socket%e7%bc%96%e7%a8%8b/