package com.nokia.sms;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.nokia.sms.message.ServerMessageUtil;

import lombok.extern.slf4j.Slf4j;

/*
 * 模拟服务器
 */
@Slf4j
public class BlkDelServer {
    // 服务端口号
    private static int port = 50000;
    private ServerSocket server = null;
    private Socket socket = null;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;
    private byte[] buffer = new byte[48];
    private byte[] message;
    private int readCount;

    public static void main(String[] args) {
        BlkDelServer server = new BlkDelServer();
        server.startServer();
    }

    private void startServer() {
        try {
            // 启动socket服务
            server = new ServerSocket(port);
            log.debug("socket服务端已在端口 {} 启动", port);
            // 接收socket连接
            Socket socket = server.accept();
            outputStream = socket.getOutputStream();
            inputStream = socket.getInputStream();
            while (true) {
                // 先读取客户端的输入
                readCount = inputStream.read(buffer);
                log.debug("收到 {} 字节 数据", readCount);
                // 识别消息 并建立 应返回的消息
                message = ServerMessageUtil.parse(buffer);
                // 向客户端输出
                outputStream.write(message);
                outputStream.flush();
            }
        } catch (IOException e) {
            log.error("服务端运行出错......");
            e.printStackTrace();
        } finally {
            close();
        }
    }

    private void close() {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
