Java REST API для отправки и получения нескольких строк через сервер сокетов и получения ответа от сервера - PullRequest
0 голосов
/ 14 сентября 2018

Я пишу API-интерфейс java-сокетов, который может отправлять сообщения на мой сокет-сервер и получать ответ от сервера.

Ниже код моего сервера:

package com.test.socket;

import java.io.*;  
import java.net.*;
import java.util.Calendar;  
public class Server {  
    /**  Instantiates an instance of the SimpleServer class and initilaizes it.
     */
    public static void main(String[] args){
        Server simpleserver = new Server();
        simpleserver.init();
    }

    /**  Sets up a ServerSocket and listens on port 8189.
     */
    public void init(){
        ServerSocket serversocket = null;
        Socket socket = null;
        try{
            //establish a server socket monitoring port 8189 
            //port 8189 is not used by any services
            serversocket = new ServerSocket(8189);
            System.out.println("Listening at 127.0.0.1 on port 8189");

            //wait indefinitely until a client connects to the socket
            socket = serversocket.accept();

            //set up communications for sending and receiving lines of text data
            //establish a bufferedreaderr from the input stream provided by the socket object
            InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            //establish an printwriter using the output streamof the socket object
            //and set auto flush on    
            PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);

            //for binary data use
            // DataInputStream and DataOutputStream

            //for serialized objects use
            // ObjectInputStream and ObjectOutputStream

            String datetimestring = (Calendar.getInstance()).getTime().toString();
            printwriter.println("You connected to the Simple Server at " + datetimestring);

            String lineread = "";
            //        boolean done = false;
            while ((lineread = bufferedreader.readLine()) != null){
                System.out.println("Received from Client: " + lineread);
                printwriter.println(lineread);
                //          if (lineread.compareToIgnoreCase("Bye") == 0) done = true;
            }

        }catch(UnknownHostException unhe){
            System.out.println("UnknownHostException: " + unhe.getMessage());
        }catch(InterruptedIOException intioe){
            System.out.println("Timeout while attempting to establish socket connection.");
        }catch(IOException ioe){
            System.out.println("IOException: " + ioe.getMessage());
        }
    }
}  

Ниже приведена функция клиента моего сокета, которая устанавливает соединение с сервером сокетов и получает ответ:

public Integer socketClient(String server_ip_address,String strToBeSent){

    int serverport = 8189;
    Socket socket = null;
    InputStreamReader inputstreamreader = null;
    BufferedReader bufferedreader = null;
    PrintWriter printwriter = null;
    int result=ConfigurationManager.FAILED_CODE;
    try{
        System.out.println("Connecting to " + server_ip_address + " on port " + serverport);
        socket = new Socket(server_ip_address,serverport);
        //Set socket timeout for 10000 milliseconds or 10 seconds just 
        //in case the host can't be reached
        socket.setSoTimeout(10000);
        System.out.println("Connected.");

        inputstreamreader = new InputStreamReader(socket.getInputStream());
        bufferedreader = new BufferedReader(inputstreamreader);
        //establish an printwriter using the output streamof the socket object
        //and set auto flush on    
        printwriter = new PrintWriter(socket.getOutputStream(),true);
        printwriter.println(strToBeSent);
        String lineread = "";
        while ((lineread = bufferedreader.readLine()) != null){
            System.out.println("Received from Server: " + lineread);
        }
        result=ConfigurationManager.SUCCESS_CODE;

    }catch(UnknownHostException unhe){
        System.out.println("UnknownHostException: " + unhe.getMessage());
        result=ConfigurationManager.FAILED_CODE;
    }catch(InterruptedIOException intioe){
        System.out.println("Timeout after communication via socket connection. Server Terminated");
        System.out.println("Closing connection.");
        result=ConfigurationManager.SUCCESS_CODE;
        try {
            bufferedreader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            inputstreamreader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printwriter.close();
    }
    catch(IOException ioe){
        System.out.println("IOException: " + ioe.getMessage());
        result=ConfigurationManager.FAILED_CODE;
    }finally{
        try{
            socket.close();
        }catch(IOException ioe){
            System.out.println("IOException: " + ioe.getMessage());
            result=ConfigurationManager.FAILED_CODE;
        }
    }
    return result;
}

Теперь каждый раз, когда я запускаю программу, хотя моя строка отправляется 2 странные вещи происходят 1) мой сервер автоматически отключается. Таким образом, после отправки первой строки, когда я делаю еще один вызов моей функции socketclient для отправки второй строки, это дает мне ошибку, поскольку сервер был прерван. 2) когда я делаю вызов метода socketclient, хотя строка была отправлена ​​на сервер, и я получаю ответ обратно. но программа доходит до блока catch catch (InterruptedIOException intioe) { System.out.println («Тайм-аут после связи через сокет-соединение. Сервер завершен»); System.out.println («Закрытие соединения»);

Вместо того, чтобы нормально закрывать мою розетку.

Могу ли я найти решение этой проблемы? Как разрешить завершение работы сервера.

...