0

我想在我的 java 服务器中创建一个 printwriter,在我的 android 代码中创建一个 buffertreader。知道我可以从我的 android 发送一条消息并在我的 java 编译器上阅读它,但我也想做相反的事情。在 android 上读取并在服务器上写入。我是否需要两个应用程序,因为我不知道是否可以将它放在尝试每个代码之间?

安卓代码:

try {

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

 printwriter.flush();
 printwriter.close();
 client.close();   //closing the connection

} catch (UnknownHostException e) {

爪哇服务器:

    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();

            System.out.println(message);
            inputStreamReader.close();
            clientSocket.close();

        } catch (IOException ex) {

感谢您花时间阅读我的问题

4

1 回答 1

0

是的,您可以在它们之间创建两种方式的通信,您所要做的就是在客户端(Android)打开一个 InputStream 并在 Java 服务器端打开一个 OutputStream,可以通过以下方式实现:

安卓代码:

try {

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

 printwriter.flush();
 printwriter.close();

 InputStream in = client.getInputStream();

 byte data[] = new byte[1024]
 in.read(data);    ///perform your reading operation here


 client.close();   //closing the connection

} catch (UnknownHostException e) {

爪哇服务器:

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();

        System.out.println(message);
        inputStreamReader.close();


        PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
        pw.write(new String("write data here"));
        pw.flush();
        pw.close();
        clientSocket.close();

    } catch (IOException ex) {
于 2013-03-27T14:18:04.703 回答