Java android套接字响应

时间:2015-06-23 13:49:02

标签: java android sockets response

我正在尝试编写Android客户端和Java服务器。

它可以从Android客户端向服务器发送消息(如果测试代码被注释掉),但我无法将响应从服务器返回给客户端。

你能帮我吗?

这是客户:

public class MainActivity extends ActionBarActivity {

private Socket client;
private PrintWriter printwriter;
private String messsage;
Button register , login;
EditText et_login_uid , et_login_pwd;
TextView backMessage;

private String serverResponse;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    register = (Button) findViewById(R.id.btn_register);
    login = (Button) findViewById(R.id.btn_login);
    et_login_uid = (EditText) findViewById(R.id.et_login_uid);
    et_login_pwd = (EditText) findViewById(R.id.et_login_pwd);
    backMessage = (TextView) findViewById(R.id.tv_hello);

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent yeni = new Intent(MainActivity.this,Register.class);
            startActivity(yeni);
        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            messsage = et_login_uid.getText().toString() + ";" + et_login_pwd.getText().toString();
            SendMessage sendMessageTask = new SendMessage();
            sendMessageTask.execute();
        }
    });

    /*login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent yeni = new Intent(MainActivity.this,Login.class);
            startActivity(yeni);
        }
    });*/
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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

    @Override
    protected Void doInBackground(Void... params) {

        try {

            client = new Socket("192.168.0.150", 4444); // connect to the server
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage); // write the message to output stream
            printwriter.flush();

            Log.i("patmaadı", "patmaladı");
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true) {
                Log.i("patladı", "patladi2");
                if ((serverResponse = in.readLine()) != null) {
                    Log.i("server says", serverResponse);
                    backMessage.setText(serverResponse);
                    break;
                }
            }
            printwriter.close();

            client.close(); // closing the connection

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

这是服务器

public class Main {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
static String DID, UID, PWD, PWDR;

private Socket client;
private PrintWriter printwriter;
private String messsage = "i'm back";

public static void main(String[] args) {
    try {
        serverSocket = new ServerSocket(4444); // Server socket

    } catch (IOException e) {
        System.out.println("Could not listen on port: 4444");
    }

    System.out.println("Server started. Listening to the port 4444");

    while (true) {
        try {

            clientSocket = serverSocket.accept(); // accept the client
                                                    // connection
            inputStreamReader = new InputStreamReader(
                    clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); // get
                                                                    // the
                                                                    // client
                                                                    // message
            message = bufferedReader.readLine();
            String[] tokens = message.split(";");
            if (tokens.length == 4) {
                register(tokens);
            } else if (tokens.length == 2) {
                login(tokens);
            }

            PrintWriter out = new PrintWriter(
                    clientSocket.getOutputStream(), true);
            out.write("i'm back");

            inputStreamReader.close();
            clientSocket.close();

        } catch (IOException ex) {
            System.out.println("Problem in message reading");
        }
    }

}

static void login(String tokens[]) {

    for (String t : tokens) {
        UID = tokens[0];
        PWD = tokens[1];

        System.out.println(UID + PWD);

    }
}

static void register(String tokens[]) {

    for (String t : tokens) {
        DID = tokens[0];
        UID = tokens[1];
        PWD = tokens[2];
        PWDR = tokens[3];

    }

    System.out.println(DID + " " + UID + " " + PWD + " " + PWDR);
    database();
}

static void database() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = null;
        conn = DriverManager.getConnection("jdbc:mysql://localhost/cankat",
                "root", "");
        System.out.print("Database is connected !");
        Statement stt = conn.createStatement();

        if (PWD.equals(PWDR)) {
            stt.executeUpdate("INSERT INTO users " + "VALUES ('" + DID
                    + "','" + UID + "','" + PWD + "')");
        } else {
        }
        conn.close();
    } catch (Exception e) {
        System.out.print("Do not connect to DB - Error:" + e);
    }
}
}

0 个答案:

没有答案