2016-12-30 2 views
0

Я создал Java-сервер с именем server.java, используя java-сокеты, который принимает строку от клиента (client.java) на Android, изменяет ее и отправляет измененную строку клиенту [ в моем случае это приложение для Android].Нужна помощь в Java Socket Programming [server & client]

Когда я попытался запустить оба из них, без каких-либо ошибок приложение Android успешно отправляет введенную пользователем строку на сервер. Проблема возникает, когда сервер получает строку, иногда сервер не предоставляет никакого вывода. Но если клиент закрыт (или убит), то терминальные сервера выходов как:

message received from client is: null 
request: Message sent to the client : i received message:null 
message received from client is: null 
request: Message sent to the client : i received message:null 
message received from client is: null 
request: Message sent to the client : i received message:null 
message received from client is: null 
request: Message sent to the client : i received message:null 
message received from client is: null 
request: Message sent to the client : i received message:null 

Вот код Server.java, который работает в настольном компьютере:

public class Server { 
    static Socket socket; 
    static PrintWriter out; 
    static BufferedReader in; 
    static int port = 9999; 

    public static void main(String[] args) { 

     String query="blank", returnMessage="Server malfunctioning!"; 

     try { 
      ServerSocket serverSocket = new ServerSocket(port); 
      System.out.println("Server Started and listening to the port "+port); 
      socket = serverSocket.accept(); 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 

      while(true) { 
       try { 
        query=in.readLine(); 
        System.out.println("message received from client is: "+query); 
        //Processing the query. 
        returnMessage="i received message:"+query; 

        //Sending the response back to the client. 
        out.print(returnMessage); 
        System.out.println("request: Message sent to the client : " + returnMessage); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
        out.flush(); 
        out.close(); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       socket.close(); 
      } catch(Exception e) { 
       System.out.println(e); 
      } 
     } 
    } 
} 

А вот ServerConnect.java, который проходит AsyncTask :

public class ServerConnect extends AsyncTask<Object, Object, Void> { 
    String TAG="Server"; 
    String message="empty response"; 
    String ip="EMPTY QUERY"; 
    WebView wb; 
    TextToSpeech tts; 
    String host = "192.168.2.3"; 
    int port = 9999; 
    PrintWriter out; 
    BufferedReader in; 
    Socket socket; 

    ServerConnect(String inp, WebView wbb, TextToSpeech ts) { 
     ip=inp; 
     this.wb=wbb; 
     tts=ts; 
    } 

    @Override 
    protected Void doInBackground(Object... voids) { 
     Log.d(TAG, "ip value "+ip); 
     try { 
      // InetAddress address = InetAddress.getByName(host); 
      socket = new Socket(host, port); 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      try { 
       //Send the message to the server 
       out.print(ip); 
       //out.flush(); 
       Log.d(TAG, "request: Message sent to the server : " + ip); 
       message = in.readLine(); 
       Log.d(TAG, "doInBackground: message" + message); 
      } catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       message = "UnknownHostException: " + e.toString(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       message = "My Brain is not working! Reason is: "+e; 
      } finally { 
       in.close(); 
       out.flush(); 
      } 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      Log.d(TAG, "doInBackground: finally block"); 

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

     return null; 
    } 

    protected void onPostExecute(Void result) { 
     // wb.getSettings().setJavaScriptEnabled(true); 
     if(message!=null) { 
      wb.loadDataWithBaseURL(null, message, "text/html", "utf-8", null); 
      tts.speak(stripHtml(message), TextToSpeech.QUEUE_FLUSH, null, null); 
      if (!(pullLinks(stripHtml(message)).equals(""))) { 
       wb.setWebViewClient(new WebViewClient()); 
       wb.setWebChromeClient(new WebChromeClient() {}); 
       wb.loadUrl(pullLinks(message)); 
       //ip.setText(""); 
       super.onPostExecute(result); 
      } 
     } else { 
      wb.loadDataWithBaseURL(null, "Message is null!", "text/html", "utf-8", null); 
      tts.speak("Message is null!", TextToSpeech.QUEUE_FLUSH, null, null); 
     } 
    } 

    public String stripHtml(String html) { 
     return Html.fromHtml(html).toString(); 
    } 

    private String pullLinks(String text) { 
     String links=""; 

     String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]"; 
     Pattern p = Pattern.compile(regex); 
     Matcher m = p.matcher(text); 

     while(m.find()) { 
      String urlStr = m.group(); 
      if (urlStr.startsWith("(") && urlStr.endsWith(")")) 
       urlStr = urlStr.substring(1, urlStr.length() - 1); 

      links=urlStr; 
     } 

     return links; 
    } 
} 
+0

Могу ли я предложить вашу существующую технологию для создания клиент-серверной связи? – Sergey

+0

попытайтесь очистить автора в конце на стороне сервера – PWC

+0

Создайте поток для обработки ввода и вывода. Первый подключенный клиент блокирует все остальные клиенты. – PWC

ответ

0

readLine() возвращает нулевое значение в конце потока, т.е. когда собеседник закрывает соединение. Вы не обнаруживаете этот случай: вы обрабатываете null как данные. Вы должны прервать цикл чтения, когда вы получите нуль.

NB UnknownHostException не может быть выброшен либо print(), либо readLine().