java - Android客户端/Java服务器通信,无法接收服务器返回的数据

标签 java android client server serversocket

我在将某些内容从服务器发送回客户端时遇到问题。 这段代码只将数据从Android客户端发送到服务器,我无法让它从服务器发送回Android客户端。我尝试将 Inputstream reader 放入客户端代码中,但似乎不起作用。 这是代码: 客户端代码:

package com.lakj.comspace.simpletextclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

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

/**
* This is a simple Android mobile client
* This application read any string massage typed on the text field and 
* send it to the server when the Send button is pressed
* Author by Lak J Comspace
*
*/
public class SlimpleTextClientActivity extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_slimple_text_client);

    textField = (EditText) findViewById(R.id.editText1); // reference to the text field
    button = (Button) findViewById(R.id.button1); // reference to the send button

    // Button press event listener
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            messsage = textField.getText().toString(); // get the text message on the text field
            textField.setText(""); // Reset the text field to blank
            SendMessage sendMessageTask = new SendMessage();
            sendMessageTask.execute();
        }
    });
}

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

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

            client = new Socket("10.0.2.2", 4444); // connect to the 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) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

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

}

服务器代码:

package com.lakj.comspace.simpletextserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
* This is a simple server application. This server receive a string message
* from the Android mobile phone and show it on the console.
* Author by Lak J Comspace
*/
public class SimpleTextServer {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;

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

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

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

}

}

最佳答案

套接字是“双向的”。您需要在客户端的 getInputStream 和服务器端的同一端口/套接字上的 getOutputStream。 添加到客户端:

client = new Socket(IP, PORT); // second connection to server
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
inputStreamReader.close();            
socket.close();   //closing the connection

& 到服务器:

printWriter = new PrintWriter(clientSocket.getOutputStream(), true);
printWriter.write("Returned back from server to client \n");  //write the message to output stream
printWriter.flush();                  
printWriter.close(); 
inputStreamReader.close();             
clientSocket.close();

关于java - Android客户端/Java服务器通信,无法接收服务器返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27804330/

相关文章:

android - Bing 翻译 Android 设置语言

android - 当屏幕变为非 Activity 状态时,计时器似乎正在暂停

c# - 使用 HttpWebRequest/Response 构建 .NET REST 客户端有什么缺点吗

java - 持久 TCP 连接客户端/服务器

java ;当文件中的字符串打印在屏幕上时,空值也会随之打印在末尾

java - 我应该评论我的测试吗?

java:如何通过类加载器获取单例实例

java - 每 x 次执行一项任务

android - 如何解决 "App is having trouble with google play services. please try again."

c++ - 如何使用传入套接字识别(或连接)用户标识?