无法在本地通过wifi连接Pc / Android

时间:2012-04-20 14:26:31

标签: java android sockets wifi lan

我正在开发一款需要在PC和Android之间交换消息的游戏。 PC(192.168.2.104)和Android(192.168.2.160)连接到同一路由器,但无法交换消息。我可以使用VM运行它但不使用智能手机,连接超时并且应用程序停止。 Android和Windows 7 PC使用的版本是2.3.4。 以下是关于连接的Android代码:

public class Connetti extends Activity {
EditText txtIp;
EditText txtNick;
TextView lblConferma;
Button btnConnetti;
static String serverIp;
static String nickname;
Socket socket = null;
DataOutputStream dataOutputStream = null;


public static String getIp(){
    return serverIp;
}

public static String getNick(){
    return nickname;
}

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* fullscreen */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.connetti);
        /* gui */
         txtIp= (EditText)findViewById(R.id.txtIp);
         txtNick= (EditText)findViewById(R.id.txtNick);
         btnConnetti=(Button)findViewById(R.id.btnConnetti);
         btnConnetti.setOnClickListener(btnConnettiOnClickListener);
         lblConferma = (TextView)findViewById(R.id.lblConferma); 
 }

 Button.OnClickListener btnConnettiOnClickListener= new Button.OnClickListener(){
        /* imposta le azioni al click del bottone */
         public void onClick(View arg0) {
             btnConnetti.setClickable(false);
             /* viene salvato come stringa il contenuto dell'area di testo */
             serverIp=txtIp.getText().toString();
             nickname=txtNick.getText().toString();
             /* imposta una stringa nell'area dedicata al messaggio di conferma */
             lblConferma.setText("In attesa che l'host avvii la partita...");




             /* Inizio Connessione */
             try {

                    /* imposta la connessione verso un certo IP, tramite la porta 8888 */
                    socket = new Socket(""+serverIp, 8888);
                    dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    /* invia il nickname del giocatore al pc */
                    dataOutputStream.writeUTF(nickname);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                finally{
                    /* chiude connessione e rimuove le strutture dati per l'I/O in uscita*/
                    if (socket != null){
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    if (dataOutputStream != null){
                        try {
                            dataOutputStream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }


                }

             return;
         }
     };}

这是在PC上收听的线程的代码:

public class ThreadConnection extends Thread{
JTextArea textGiocatore;
int maxGiocatore = 6;
public InetAddress[] arrayGiocatore = new InetAddress [maxGiocatore];
int contaGiocatore = 0;
InetAddress indirizzo;
String nome;
int i=0;
boolean ctrlFlag=false;
String eol=System.getProperty("line.separator");
//int porta=8888;
public FileWriter fileIndirizzi;

public ThreadConnection(JTextArea textGiocatore){
    this.textGiocatore=textGiocatore;
}

public void creaGiocatore(int contaGiocatore, String nome, InetAddress indirizzo,FileWriter fileIndirizzi){
    try {
        fileIndirizzi.append(nome+eol);
        fileIndirizzi.append(indirizzo.getHostAddress()+eol);
        fileIndirizzi.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    textGiocatore.append("Nome del giocatore "+contaGiocatore+": "+nome+eol);
    textGiocatore.append("IP di "+nome+": "+indirizzo.getHostAddress()+eol); //se qualcosa non funziona guarda qua, indirizzo potrebbe dare problemi
    textGiocatore.append("_________________________________"+eol);
}


public void run(){
    ServerSocket serverSocket = null;
    Socket socket = null;
    DataInputStream dataInputStream = null;
//  DataOutputStream dataOutputStream = null;

    /* apertura di una connessione verso la porta 8888 */
    try {
        serverSocket = new ServerSocket(8888);
        //textArea.append("Listening :8888"+eol);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    /* creazione file in scrittura (INUTILE) */

        try{
            fileIndirizzi = new FileWriter("fileIndirizzi.txt");
        }
       catch (IOException e) {
            textGiocatore.append("Errore: " + e + eol);
            System.exit(1);
        }


    while(true){
        try {


            /* attesa di una connessione in entrata nella porta aperta in precedenza */
            textGiocatore.append("In attesa di giocatori sulla porta "+8888+eol);
            socket = serverSocket.accept();
            /* creazione strutture dati per I/O */
            dataInputStream = new DataInputStream(socket.getInputStream());
    //      dataOutputStream = new DataOutputStream(socket.getOutputStream());
            /* ottenimento IP del cellulare connesso */ 
            indirizzo=socket.getInetAddress();
            nome=dataInputStream.readUTF();




            /* inserimento e controllo degli IP nella combo box */
        if(contaGiocatore==0){
            arrayGiocatore[contaGiocatore]=indirizzo;
            creaGiocatore(contaGiocatore, nome, indirizzo, fileIndirizzi);
            contaGiocatore++;
        }
        else{
            ctrlFlag=false;
            for(i=0; i<contaGiocatore; i++){
                if((indirizzo.equals(arrayGiocatore[i])==true)){
                    ctrlFlag=true;
                }   
            }
            /* se questo flag è falso significa che l'IP non è presente nella combo box
             * e quindi viene inserito questo item
             */
            if(ctrlFlag==false){
                arrayGiocatore[contaGiocatore]=indirizzo;
                creaGiocatore(contaGiocatore, nome, indirizzo, fileIndirizzi);
                contaGiocatore++;
            }
        } 


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            if ( fileIndirizzi != null)
                try {
                    fileIndirizzi.close();
                } catch (IOException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            /* vengono chiuse la connessione e le strutture dati per l'I/O */
            if( socket!= null){
                try {
                    socket.close();
                } catch (IOException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if( dataInputStream!= null){
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

/*          if( dataOutputStream!= null){
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } */
        } 
    }

}}

Eclipse不报告错误,使用VM一切都很完美。

1 个答案:

答案 0 :(得分:0)

尝试添加:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

到你的AndroidManifest.xml。 例如:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="godard.tuatini"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:icon="@drawable/app_icon"
    android:label="@string/app_name" >
    <activity
        android:name=".activity.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

</manifest>

此外,您应该将应用程序的网络部分放在一个线程中。对于Android使用AsyncTask来做到这一点。