Java TcpConnection

时间:2018-10-04 06:43:52

标签: java android tcp

你好,我有一个用Java编写的代码,我需要在android studio中用GPS设备创建一个TCP连接,如果有人可以帮助我,请在这里输入IP / PORT地址。

public class TCPConnection implements Runnable {

/**
 * <h1>TCP Connection construct</h1>
 * <p>The tcp connection requires two parameters socket and view model. </p>
 * @param socket to establish connection.
 * */





TCPConnection(Socket socket) {
    super();
    this.socket = socket;
    converter = new Converter();
    crc16 = new Crc16();
}






/**
 * <h1>Run function to start listener</h1>
 * <p>Simply runs the runnable thread to listen everything from client</p>
 * */

public void run() {
    try {
        inputStream = new DataInputStream(socket.getInputStream());
        outputStream = new DataOutputStream(socket.getOutputStream());
        Listen();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

可能我需要创建一个按钮来开始监听传入的连接,也要使用Log类.....

 /**
 * <h1>Listen</h1>
 * <p>Function for listening connected client</p>
 * @throws IOException throws exception if input stream is interrupted
 * */
private void Listen() throws IOException {
    while (flag) {
        System.out.println("listening...");
        while (!socket.isClosed() && inputStream.available() == 0) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
        Communicate();
    }
    inputStream.close();
    outputStream.close();
    socket.close();
}











/**
 * <h1>Get Number Of Records</h1>
 * <p>Reads the number of records to send back to the sender</p>
 * @param data the parameter is a received hex data
 * @return String format number of records
 * */
private String GetNumberOfRecords(String data) {
    return data.substring(18, 20);
}

所有内容都写在注释行中,为什么stackoverflow表示添加更多详细信息:D ...

/**
 * <h1>Communicate</h1>
 * <p>A reader and sender with client, first it reads imei, then sends back 01.
 * It receives data, as soon it receives it sends back number of records.
 * The while loop initializes and runs until it get interrupted or client disconnects.</p>
 * */
private void Communicate()  {

    imei =  Objects.requireNonNull(ReadInput()).substring(4);
    imei = converter.ReadImei(imei);
    String path = System.getProperty("user.home") + "/Desktop";
    logger = new Logger(path+"/Logs/TCPLogs/"+imei);
    logger.PrintToLOG(GetTime()+" IMEI: " +imei);
    if(imei.length() < 15){
        SendOutput("00");
    }
    else{
        SendOutput("01");
        logger.PrintToLOG("\tResponse: [0" + 1 + "]");
        String input = ReadInput();
        Log(Objects.requireNonNull(input));
        while(flag){
            String recordsCount = GetNumberOfRecords(input);
            SendOutput("000000" + recordsCount);
            logger.PrintToLOG("\tCrc: " + Integer.toHexString(CRC(input)));
            logger.PrintToLOG("\tResponse: [000000" + recordsCount + "]\n");
            input = ReadInput();
            Log(Objects.requireNonNull(input));
        }
    }


/**
 * <h1>Send Output</h1>
 * <p>Sends output to the client</p>
 * @param message the parameter is a received hex data
 * */
private void SendOutput(String message)  {
    try {
        outputStream.write(converter.StringToByteArray(message));
        outputStream.flush();
    } catch (IOException e) {
        System.out.println("Output stream was interrupted");
    }
}








/**
 * <h1>CRC</h1>
 * <p>Calculates CRC of received data</p>
 * @param str the parameter is a received hex data
 * @return int of crc16
 * */
private int CRC(String str) {
    str = str.substring(16, str.length() - 8);
    byte[] bytes = converter.StringToByteArray(str);
    return crc16.getCRC(bytes);
}












/**
 * <h1>Read Input</h1>
 * <p>Reads the input from client. Currently maximum message byte is set up to 8192,
 * if message is bigger then message will not be properly readable and displayed.</p>
 * @return String of received data
 * */
private String ReadInput() {
    byte[] messageByte = new byte[8192];
    int dataSize;
    try {
        dataSize = inputStream.read(messageByte);
        String finalInput = converter.BytesArrayToHex(messageByte, dataSize);
        SendToConsole(finalInput);
        return finalInput;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}














/**
 * <h1>Send To Console</h1>
 * <p>Simply prints out the results to the text area for user</p>
 * @param input the parameter is String format to print in text area
 * */
private void SendToConsole(String input) {
    if(imei!=null)
    {
        String message = viewModel.getClientMessage() + "\r\nFrom imei - "+imei+" : " + input + "\n" + repeatChar();
        Platform.runLater(() -> viewModel.setClientMessage(message));
    }
    else {
        String message = viewModel.getClientMessage() + "\r\nReceived imei - : " + input + "\n" + repeatChar();
        Platform.runLater(() -> viewModel.setClientMessage(message));
    }
}        









/**
 * <h1>Log</h1>
 * <p>Given String is being written to log file.</p>
 * @param data the parameter is a received data
 * */
private void Log(String data) {
    logger.PrintToLOG("\tcodec             : " + data.substring(16, 18));
    logger.PrintToLOG("\tNumber of Records : " + GetNumberOfRecords(data));
    logger.PrintToLOG("\tAVL data          : " + data + "\n");
}

/**
 * <h1>Set Running</h1>
 * <p>Sets flag to run or stop while loop in order to interrupt the thread.</p>
 * */
void setRunning() {
    this.flag = false;
}

/**
 * <h1>Repeat Char</h1>
 * <p>Repeats the '=' character multiple times.</p>
 * @return String is being returned.
 * */
private String repeatChar() {
    char[] data = new char[50];
    Arrays.fill(data, '=');
    return new String(data);
}

/**
 * <h1>Get Time</h1>
 * <p>Gets time when method is being called</p>
 * @return Time in String format
 * */
private String GetTime()
{
    LocalDateTime localDateTime = LocalDateTime.now();
    LocalTime localTime = localDateTime.toLocalTime();
    return localTime.toString();
}


}

public class TCPServer implements Runnable {
private int port;
private Socket socket;
private ServerSocket ss;
private boolean running = true;
private ArrayList<TCPConnection> tcpConnections;

/**
 * <h1>TCP server construct</h1>
 * <p>The tcp server takes port parameter </p>
 * @param port is required for server to listen all incoming connections
 * */
public TCPServer(int port) {
    this.port = port;
}

/**
 * <h1>Run</h1>
 * <p>Runs the runnable thread to listen connections, it accepts a connection, if accept was successful,
 * the connection is added to tcpConnections list and runs the TCPConnection for further listening.
 * The server is running in while loop and stops when Running is set to false,
 * then break is called and shutdowns every connected client.</p>
 * */




public void run() {
    tcpConnections = new ArrayList<>();
    try {
        ss = new ServerSocket(port);
        System.out.println("Listening on port : " + ss.getLocalPort());
        ExecutorService executorService;
        while (true) {
            executorService = Executors.newSingleThreadExecutor();
            socket = ss.accept();
            TCPConnection connection = new TCPConnection(socket);
            executorService.submit(connection);
            tcpConnections.add(connection);
            if (!running) {
                StopConnections();
                break;
            }
        }
        executorService.shutdownNow();
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (IOException e) {
        System.out.println("socket is closed");
    }
}

/**
 * <h1>Set Flag</h1>
 * <p>Function is being called when we want to interrupt server thread and stop it.</p>
 * @param flag the parameter sets whenever to true(run server) or false(stop server)
 * */
public void setFlag(boolean flag) {
    running = flag;
    if (!running) {
        try {
            ss.close();
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            System.out.println("Socket is " + socket.isClosed());
        }
    }
}

/**
 * <h1>Stop Connections</h1>
 * <p>Function is being called when we are stopping server,
 * this function iterates through every connection and stops it.</p>
 * */
private void StopConnections() {
    if (!tcpConnections.isEmpty()) {
        for (TCPConnection connections : tcpConnections) {
            connections.setRunning();
        }
        tcpConnections.clear();
    }
}
}

1 个答案:

答案 0 :(得分:0)

只要您的android API级别支持您正在使用的Java版本,Android就支持Java代码。没有任何理由不能在Android中使用它。

请注意,如果您在UI线程上运行任何网络任务,Android都会引发异常。例如。创建套接字应作为IntentService或AsyncTask运行,还有其他选项。