2012-04-09 25 views
6

Zajmuję się tworzeniem aplikacji Android (klient) i chcę, aby łączył się z moim serwerem Java za pomocą komunikacji TCP.Klient Android i serwer Java Komunikacja TCP

Zrobiłem kodu - prosty program, wyślij wiadomość klienta i serwera A echa go z powrotem - jak poniżej:

kod serwera:

import java.net.*; 


public class Server { 

    public static void main(String[] args) { 

     int nreq = 1; 
     try 
     { 
      ServerSocket sock = new ServerSocket (8080); 
      for (;;) 
      { 
       Socket newsock = sock.accept(); 
       System.out.println("Creating thread ..."); 
       Thread t = new ThreadHandler(newsock,nreq); 
       t.start(); 
      } 
     } 
     catch (Exception e) 
     { 
      System.out.println("IO error " + e); 
     } 
     System.out.println("End!"); 
    } 
} 

kod Handler wątek w tym samym pliku projektu serwera:

import java.io.*; 
import java.net.*; 

class ThreadHandler extends Thread { 
    Socket newsock; 
    int n; 

    ThreadHandler(Socket s, int v) { 
     newsock = s; 
     n = v; 
    } 


    public void run() { 
     try { 

      PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true); 
      BufferedReader inp = new BufferedReader(new InputStreamReader(
        newsock.getInputStream())); 

      outp.println("Hello :: enter QUIT to exit \n"); 
      boolean more_data = true; 
      String line; 

      while (more_data) { 
       line = inp.readLine(); 
       System.out.println("Message '" + line + "' echoed back to client."); 
       if (line == null) { 
        System.out.println("line = null"); 
        more_data = false; 
       } else { 
        outp.println("From server: " + line + ". \n"); 
        if (line.trim().equals("QUIT")) 
         more_data = false; 
       } 
      } 
      newsock.close(); 
      System.out.println("Disconnected from client number: " + n); 
     } catch (Exception e) { 
      System.out.println("IO error " + e); 
     } 

    } 
} 

i to po stronie klienta (Android):

package com.android.client; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.util.Scanner; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class Client extends Activity { 
    /** Called when the activity is first created. */ 
    Scanner scanner = new Scanner(System.in); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     final EditText msg = (EditText) findViewById(R.id.etMsg); 
     Button send = (Button) findViewById(R.id.bSend); 
     final TextView convo = (TextView) findViewById(R.id.tvConvo); 
     final TextView status = (TextView) findViewById(R.id.tvStatus); 

     try { 
      send.setOnClickListener(new View.OnClickListener() { 

       Socket s = new Socket("localhost", 8080); 
       String message = msg.getText().toString(); 

       @Override 
       public void onClick(View v) { 
        status.setText("..."); 
        PrintWriter outp = null; 
        BufferedReader inp = null; 
        status.setText("Established connection.."); 
        String serverMsg = null; 

        try { 
         outp = new PrintWriter(s.getOutputStream(), true); 
         inp = new BufferedReader(new InputStreamReader(s.getInputStream())); 
         serverMsg = inp.readLine(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
        convo.append(serverMsg + "\n"); 

        if (message != null) { 
         if (msg.getText().toString().trim() == "QUIT") { 
          try { 
           s.close(); 
          } catch (IOException e) { 
           e.printStackTrace(); 
          } 
          status.setText("Disconnected from server."); 

         } else { 
           try { 

            convo.append(message + "\n"); 
            outp.println(message); 
            serverMsg = inp.readLine(); 
            convo.append(serverMsg + "\n"); 
           } catch (IOException e) { 
            e.printStackTrace(); 
           } 
         } 

        } 
        else 
         status.setText("Problem in connection..!"); 
       } 
      }); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

I to jest plik XML:

<?xml version="1.0" encoding="utf-8" ?> 
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> 
    <TextView android:id="@+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Your message here:" /> 
- <EditText android:id="@+id/etMsg" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10"> 
    <requestFocus /> 
    </EditText> 
    <TextView android:id="@+id/tvStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status..." android:textAppearance="?android:attr/textAppearanceSmall" /> 
    <Button android:id="@+id/bSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" /> 
    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Conversation:" android:textAppearance="?android:attr/textAppearanceLarge" /> 
    <TextView android:id="@+id/tvConvo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> 
    </LinearLayout> 

Próbowałem uruchomić go, ale nic się nie dzieje. Po kliknięciu przycisku TextView nie wyświetla komunikatu "Hello" z serwera.

+0

Czy masz "' ustawione w pliku manifest.xml? – diewie

+0

Tak, istnieje zezwolenie w Internecie –

Odpowiedz

9

Połączysz się z klientem z systemem Android pod numerem localhost.

Socket s = new Socket("localhost", 8080); 

Działa to tylko wtedy, gdy serwer działa na urządzeniu z systemem Android. Ale myślę, że działa na twoim komputerze. Po uruchomieniu aplikacji na emulatorze Androida możesz połączyć się z 10.0.2.2, aby skontaktować się z hostem. Na prawdziwym urządzeniu musisz znaleźć adres IP swojego serwera, do którego może dotrzeć urządzenie z systemem Android, np. przez Wi-Fi.

+0

Dziękuję bardzo! To się udało. –

+0

Witaj Diewie, próbuję połączyć klienta (Android) z komputerem przez Internet, jak mogę to zrobić? - Próbowałem połączyć się przez WiFi i zadziałało, zastępując 10.2.0.0 adresem IP mojego laptopa. –

+1

To zadziała tylko wtedy, gdy komputer będzie można bezpośrednio połączyć z Internetem lub istnieją odpowiednie reguły przekierowania portów. Jaka jest twoja obecna konfiguracja? – diewie

0

Jeśli twój serwer jest w systemie Windows, wpisz cmd w polu wyszukiwania menu Start, a następnie wpisz ipconfig w wierszu polecenia. Zobaczysz coś takiego jak IVP4 Address----- 192.168.0.101. musisz użyć tego adresu i numeru portu na kliencie.

Powiązane problemy