在Android应用程序中使用套接字

时间:2015-11-14 20:53:15

标签: android sockets

我最近做了一个简单的多播客户端 - 用于java的服务器聊天,现在我试图在android上移植客户端。

我面临的问题是关于处理套接字:套接字是在一个线程中创建的(因为它会使应用程序崩溃),然后我使用套接字来实现一个InputStreamReader和一个OutputStreamWriter,但是在尝试时要通过按钮侦听器访问以这种方式创建的任何对象,我将获得一个null异常。 另外,如果我将两个读者放在线程之外,他们也会生成一个null异常,即使我确保已经在线程中创建了套接字。

如果有人能帮助我找出问题所在,我会很高兴,我为凌乱的代码道歉

public class ClientActivity extends AppCompatActivity {
public static int PORT = 1050;
public static String ADDRESS = "";
public static String USERNAME = "";
SusListenerThread inT;
public int ID;
public int roomID;
Socket socket = null;
BufferedReader in = null, stdIn = null;
PrintWriter out = null;
InputStreamReader isr;
OutputStreamWriter osw;
String userInput="";
public int mode=1;
public Button Bsend;
public Button Bbroadcast;
public Button Broom;
public EditText editMessage;
public EditText editReplies;
public EditText editRoom;
public TextView txtID;
public TextView txtUsername;
public TextView txtRoom;
public connectSocket coSocket;
public ClientActivity() {

}


public void setStuff(String str, int IDh){
    this.ID=IDh;
    this.USERNAME=str;
    txtID.setText("ID: "+IDh);
    txtUsername.setText("Username: "+str);

}

private class SusListenerThread extends Thread{
    BufferedReader in = null;
    public int ID;
    public String username;
    public boolean isSet=false;
    //public View viiv;
    public EditText editReplies;
    public TextView txtRoom;

    public SusListenerThread(InputStreamReader isr){
        //this.viiv=viiv;

        //editReplies = (EditText)viiv.findViewById(R.id.editReplies);
        //txtRoom = (TextView)viiv.findViewById(R.id.textRoom);

        in = new BufferedReader(isr);
        //ClientGUI.jTextArea1.append(joj+"\n");
        start();
    }

    @Override
    public void run(){
        String input="";
        getStuff();

        while(true)
        {
            try {
                input=in.readLine();
            } catch (IOException ex) {
                //Logger.getLogger(ListenerThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            if(input.charAt(0)=='0')
                //ClientGUI.jTextArea1.append(input.substring(1)+"\n");
                editReplies.append(input.substring(1)+"\n");
            else if(input.charAt(0)=='1'){
                //ClientGUI.jLabel2.setText("Stanza:"+input.substring(1));
                txtRoom.setText("Room: "+input.substring(1));
            }
        }
    }
    public void getStuff(){

        try {
            ID=Integer.parseInt(in.readLine());
            username+=in.readLine();
        } catch (IOException ex) {

        }
        isSet=true;
    }
}

private class connectSocket extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPostExecute(Void result) {


    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            socket= new Socket(ADDRESS,PORT);

        } catch (IOException e) {
            try {
                socket = new Socket("127.0.0.1", 1050);
            }catch(Exception ex){
                e.printStackTrace();
            };
        }
        /*
        try{
            isr = new InputStreamReader ( socket.getInputStream());
            //in = new BufferedReader(isr);
            inT=new SusListenerThread(isr);
            osw = new OutputStreamWriter ( socket.getOutputStream());
            BufferedWriter bw = new BufferedWriter( osw );
            out = new PrintWriter (bw, true);


        } catch (IOException ex) {}
        */
        return null;
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

private class lilThread extends Thread {
    public lilThread(){
        start();

    }
    @Override
    public void run(){
        try {
            socket = new Socket(ADDRESS, PORT);
        }catch(Exception e ){
            try {
                socket = new Socket("79.42.49.56", 1050);
            } catch (IOException ex) {ex.printStackTrace();}
        }
        try {
            isr = new InputStreamReader ( socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        inT=new SusListenerThread(isr);

        try {
            osw = new OutputStreamWriter ( socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter bw = new BufferedWriter( osw );
        out = new PrintWriter (bw, true);

        while(!inT.isSet){
            try {
                wait(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        setStuff(inT.username.substring(4)/*Mi ritornava nullUtente invece di Utente*/, inT.ID);

        try {
            wait(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interrupt();
    }
}

public void InitializeStuff(){
    lilThread lil = new lilThread();
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_activity_gui);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Bsend = (Button)findViewById(R.id.buttonSenderino);
    Bbroadcast = (Button)findViewById(R.id.buttonBroadcast);
    Broom = (Button)findViewById(R.id.buttonRoom);
    editMessage = (EditText)findViewById(R.id.editMessage);
    editReplies = (EditText)findViewById(R.id.editReplies);
    editRoom = (EditText)findViewById(R.id.editRoom);
    txtID = (TextView)findViewById(R.id.textID);
    txtUsername = (TextView)findViewById(R.id.textUsername);
    txtRoom = (TextView)findViewById(R.id.textRoom);



    this.PORT = getIntent().getExtras().getInt("PORT");
    this.ADDRESS = getIntent().getExtras().getString("ADDRESS");
    this.USERNAME = getIntent().getExtras().getString("USERNAME");

    InitializeStuff();

    Bsend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //userInput= (EditText)v.findViewById(R.id.editMessage).getco;
            userInput = editMessage.getText().toString();
            if (!"".equals(userInput)) {
                out.println(3 + userInput);
                editMessage.setText("");
            }
        }
    });
    Bbroadcast.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mode=0;
            txtRoom.setText("Room: Broadcast");
            roomID=-1;
            out.println(mode);
            editMessage.setText("");
        }
    });
    Broom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mode=2;
            try{
                roomID=Integer.parseInt(editRoom.getText().toString());
                txtRoom.setText("Stanza: "+roomID);
                out.println(mode+""+roomID);
                editRoom.setText("");
            }catch(Exception e){
                txtRoom.setText(" Err ");
            }
        }
    });
}

}

0 个答案:

没有答案