socket 消息收发实现(socket设置采用配置文件方式)

Posted adao21

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket 消息收发实现(socket设置采用配置文件方式)相关的知识,希望对你有一定的参考价值。

闲话少叙,废话省略。。。

配置文件:application.properties

#socket server config
socket.server.address = 192.168.127.220
socket.server.port = 2000
socket.connect.timeout = 3000

配置文件获取工具类:PropertiesUtil

package com.adao.simulater.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 获取配置内容
 * 
 * @author adao
 *
 */
public class PropertiesUtil {

    public static Properties loadProperties() throws IOException {
        Properties properties = new Properties();
        InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties");
        properties.load(in);
        in.close();
        return properties;

    }

}

 

客户端:SocketClient

package com.adao.simulater.socket2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Properties;

import com.adao.simulater.common.PropertiesUtil;

/**
 * socket 客户端 模拟及时聊天
 * 
 * @author adao 2020-06-19
 */
public class SocketClient {

    private static Properties resource = null;

    public static void main(String[] args) throws IOException {

        resource = PropertiesUtil.loadProperties();
        String serverAddress = resource.getProperty("socket.server.address");
        int serverPort = Integer.valueOf(resource.getProperty("socket.server.port"));
        int connectTimeout = Integer.valueOf(resource.getProperty("socket.connect.timeout")); // 超时时间
        Socket socket = new Socket();
//        socket.setSoTimeout(3000);  //超时时间

//        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000), 3000);
        socket.connect(new InetSocketAddress(serverAddress, serverPort), connectTimeout);

        System.out.println("已发起链接");
        System.out.println("客户端,IP:" + socket.getLocalAddress() + ",port:" + socket.getLocalPort());
        System.out.println("服务器,IP:" + socket.getInetAddress() + ",port:" + socket.getPort());

        try {
            todo(socket);
        } catch (IOException e) {
            System.out.println("出现异常");
        } finally {
            socket.close();
            System.out.println("客户端退出");
        }
    }

    private static void todo(Socket socket) throws IOException {
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        // 得到Socket输出流,并转换为打印流
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);

        // 获取Socket的输入流
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            String s = input.readLine(); // 获取键盘输入
            printStream.println(s); // 打印流打印键盘输入

            String back = bufferedReader.readLine(); // 获取服务端的返回结果 获取服务端的返回结果就是获取服务端输入给客户端的消息,所以用输入流
            if ("bye".equals(back) || "exit".equals(back)) {
                flag = false;
            }
            System.out.println(back);
        } while (flag);

        printStream.close();
        bufferedReader.close();
    }

}

服务端: SocketServer

package com.adao.simulater.socket2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

import com.adao.simulater.common.PropertiesUtil;

/**
 * socket 服务端 模拟及时聊天
 * 
 * @author adao 2020-06-19
 */
public class SocketServer {
    private static Properties resource = null;

    public static void main(String[] args) throws IOException {

        resource = PropertiesUtil.loadProperties();
        int serverPort = Integer.valueOf(resource.getProperty("socket.server.port"));
        ServerSocket serverSocket = new ServerSocket(serverPort);

        System.out.println("服务器已准备就绪");
        System.out.println("服务器,IP:" + serverSocket.getLocalSocketAddress() + ",port:" + serverSocket.getLocalPort());

        // 等待客户端连接
        while (true) {
            Socket client = serverSocket.accept(); // 等待客户端连接
            ClientHandler clientHandler = new ClientHandler(client);
            clientHandler.setName("socket_server_" + i);
            clientHandler.start();
            System.out.println("Socket server name :" + clientHandler.getName());
        }

    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket s) {
            this.socket = s;
        }

        @Override
        public void run() {
//            System.out.println("Thread name:" + getName());
            System.out.println(
                    "Thread name:" + getName() + "新客户端连接,IP:" + socket.getInetAddress() + ",port:" + socket.getPort());
            try {
                // 获取服务端打印流,用来给客户端返回消息
                PrintStream printStream = new PrintStream(socket.getOutputStream());
                // 获取服务端的输入流
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                do {
                    String input = socketInput.readLine(); // 获取客户端发送给服务端的消息
                    if ("bye".equals(input)) {
                        flag = false;
                        printStream.println("bye"); // 回复客户端 也就是给客户端的输入流输入消息
                    } else {
                        System.out.println(input);
                        printStream.println("您输入的消息长度是:" + input.length()); // 回复客户端 也就是给客户端的输入流输入消息
                    }
                } while (flag);

                socketInput.close();
                printStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("客户端已退出,IP:" + socket.getInetAddress() + ",port:" + socket.getPort());
        }
    }

}

 

执行结果:

客户端打印截图:

技术图片

 

 

 服务端打印截图:

技术图片

 

 

完美。

 

以上是关于socket 消息收发实现(socket设置采用配置文件方式)的主要内容,如果未能解决你的问题,请参考以下文章

socket收发消息原理剖析

团队项目

python-利用socket客户端服务端循环收发消息

客户端服务端循环收发消息

python-利用socket客户端服务端循环收发消息

服务端循环链接请求来收发消息