2016-12-02 68 views
0

我在「世界,你好」 客戶端/服務器應用程序工作,我與服務器之間的連接,這是寫在並運行我的電腦上掙扎和客戶端,這是寫在安卓並在我的手機上運行。簡單使用客戶端 - 服務器應用插座

我連接了兩個應用程序在同一個子網上,我的路由器,併爲他們設置相應的IP和端口。 問題是,用Android編寫的客戶端瞬間停止。

P.S.出於安全原因,我沒有發佈我的IP地址。

服務器代碼是:

import java.net._ 
import java.io._ 
import scala.io._ 

object MyServer extends App 
{ 
    try 
    { 
     val server = new ServerSocket(4242) 
     println("Serve initialized:") 
     val client = server.accept 

     val in = new BufferedReader(new InputStreamReader(client.getInputStream())) 
     val out = new PrintStream(client.getOutputStream()) 
     var message =in.readLine() 
     while(message != null) 
     { 
     println("Server received:" + message) 
     out.println("Message received") 
     out.flush 
     if (message.equals("Disconnect")) 
      { 
      client.close; 
      server.close; 
      println("Server closing:") 
      } 
      message= in.readLine() 
     } 
    } 

    catch 
    { 
     case e: Exception => println(e.getStackTrace); System.exit(1) 
    } 
} 

的客戶端代碼:

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.ghiurutan.clientv1.MainActivity"> 

    <Button 
     android:text="@string/button_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/button" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="158dp" /> 

    <TextView 
     android:text="@string/text_view_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignTop="@+id/editText" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:id="@+id/textView" 
     android:layout_alignBottom="@+id/editText" 
     android:layout_toLeftOf="@+id/button" 
     android:layout_toStartOf="@+id/button" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="textPersonName" 
     android:ems="10" 
     android:id="@+id/editText" 
     android:layout_marginBottom="125dp" 
     android:layout_alignBottom="@+id/button" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" /> 

</RelativeLayout> 

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.ghiurutan.clientv1"> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

MainActivity.java

package com.example.ghiurutan.clientv1; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import java.io.*; 
import java.net.*; 
import android.view.View; 
import android.widget.*; 



public class MainActivity extends AppCompatActivity { 
    private Socket socket; 
    private static final int SERVER_PORT=4242; 
    private static final String SERVER_IP=""; 
    private EditText editText; 
    private Button button; 
    private PrintWriter printWriter; 
    private String messageToSend; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new Thread(
       new Runnable() 
       { 
        public void run() 
        { 
         try{ 
          socket=new Socket(InetAddress.getByName(SERVER_IP),SERVER_PORT); 
         }catch(UnknownHostException e) 
         { 
          System.out.println(e.getLocalizedMessage()); 
         }catch(IOException e) 
         { 
          System.out.println(e.getLocalizedMessage()); 
         } 
        } 
       } 
     ).start(); 

    } 

    @Override 
    protected void onStart() 
    { 
     super.onStart(); 

     try{ 
      printWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); 
     }catch(UnknownHostException e) 
     { 
      System.out.println(e.getLocalizedMessage()); 
     }catch(IOException e) 
     { 
      System.out.println(e.getLocalizedMessage()); 
     } 

     editText=(EditText)findViewById(R.id.editText); 
     button=(Button)findViewById(R.id.button); 

     button.setOnClickListener(
       new Button.OnClickListener() 
       { 
        public void onClick(View v) 
        { 
         messageToSend=editText.getText().toString(); 
         editText.setText(""); 
         printWriter.println(messageToSend); 
        } 
       } 
     ); 
    } 

    @Override 
    protected void onResume() 
    { 
     super.onResume(); 
    } 

    @Override 
    protected void onPause() 
    { 
     super.onPause(); 
    } 

    @Override 
    public void onDestroy() 
    { 
     super.onDestroy(); 
    } 
} 

我必須提到,我只是編程的初學者,因此歡迎任何幫助或建議。 我應該在這種情況下使用端口轉發嗎?有人告訴我,把服務器放在雲上是一個好主意,因爲那樣會更明顯。

+0

'併爲them'相應的IP和端口。不清楚。你做了什麼? – greenapps

+1

我看到的第一個問題是,你不是在一個線程中的所有網絡代碼。是的,你打開線程中的套接字。好。但不是印刷作家和println()。所有網絡代碼應該在線程或AsyncTask中執行。 – greenapps

+0

所以你會在logcat中清楚地看到一個'NetworkOnMainThreadException'。而這會讓你的應用崩潰。你沒有報告。 – greenapps

回答

1

最後的代碼,實際工作,如下:

package com.example.ghiurutan.clientv1; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import java.io.*; 
import java.net.*; 
import android.view.View; 
import android.widget.*; 



public class MainActivity extends AppCompatActivity { 
    private Socket socket; 
    private static final int SERVER_PORT=8888; 
    private static final String SERVER_IP="192.168.100.2"; 
    private EditText currentEditText,destinationEditText; 
    private TextView resultTextView; 
    private Button button; 
    private PrintWriter printWriter; 
    private BufferedReader bufferedReader; 
    private String currentLocationMessage, 
    destinationLocationMessage,messageReceived; 

//Called when the activity is first created 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     button=(Button)findViewById(R.id.button); 
     currentEditText=(EditText)findViewById(R.id.editText1); 
     destinationEditText=(EditText)findViewById(R.id.editText2); 
     resultTextView=(TextView)findViewById(R.id.textView4); 


     button.setOnClickListener(
        new Button.OnClickListener() { 
        public void onClick(View v) { 

         currentLocationMessage = currentEditText.getText().toString(); 
         destinationLocationMessage=destinationEditText.getText().toString(); 
         currentEditText.setText(""); 
         destinationEditText.setText(""); 
         new Thread(new SendMessage()).start(); 
        } 
       } 
     ); 
    } 


    private class SendMessage implements Runnable { 
     public void run() { 
      try { 
       String inputMessage=currentLocationMessage+"#"+destinationLocationMessage; 
       socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT); 
       printWriter = new PrintWriter(socket.getOutputStream()); 
       bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); 
       printWriter.println(inputMessage); 
       printWriter.flush(); 
       currentLocationMessage=""; 
       destinationLocationMessage=""; 
       messageReceived = bufferedReader.readLine(); 

       runOnUiThread(new Runnable(){ 
        @Override 
        public void run() 
        { 
         if(messageReceived==null || messageReceived.equals("")) 
         { 
          resultTextView.setText("Error.Please check the inputs."); 
         }else { 
          resultTextView.setText(messageReceived); 
         } 
        } 
       }); 
       printWriter.close(); 
       bufferedReader.close(); 
       socket.close(); 

      } catch (UnknownHostException e) { 
       System.out.println(e.getLocalizedMessage()); 
      } catch (IOException e) { 
       System.out.println(e.getLocalizedMessage()); 
      } 
     } 

    } 


//Called when the activity is about to become visible 
    @Override 
    protected void onStart() 
    { 
     super.onStart(); 
    } 

    //Called when the activity has become visible 
    @Override 
    protected void onResume() 
    { 
     super.onResume(); 
    } 

    //Called when another activity is taking focus 
    @Override 
    protected void onPause() 
    { 
     super.onPause(); 
    } 

    //Called before the activity is destroyed 
    @Override 
    public void onDestroy() 
    { 
     super.onDestroy(); 
    } 
}