java - android客户端与java服务器通信

标签 java android

我们正在开发一个android应用程序。它基本上涉及客户端服务器通信。客户端是android手机,服务器是java。客户端和服务器发生通信。期望客户端向服务器发送消息,服务器响应返回客户端。但实际上客户端能够将消息发送到服务器,但服务器无法或发送错误的响应。我不明白为什么会发生这种情况。 这是客户端代码(android):

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
public TextView accept;
private Button button;
private String message;
private static BufferedReader bufferedReader;
public static InputStreamReader inputStreamReader;
String response;
DataInputStream dis;
static String Extra_message = "hkrw.clientside";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textField = (EditText) findViewById(R.id.editText1);
    button = (Button) findViewById(R.id.button1);
    this.accept = (TextView) findViewById(R.id.accept);


    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            message = textField.getText().toString();
            textField.setText("");
            SendMessage sendMessageTask = new SendMessage();
            sendMessageTask.execute();
            accept.setText(response);
        }
    });
}

private class SendMessage extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        DataOutputStream dataOutputStream = null;
        DataInputStream smalldataInputStream = null;
        try {
            client = new Socket("192.168.1.6", 4446);
            printwriter = new PrintWriter(client.getOutputStream(), true);
            inputStreamReader = new InputStreamReader(client.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);
            printwriter.write(message);
           // smalldataInputStream = new DataInputStream(client.getInputStream());

            printwriter.flush();
            printwriter.close();
            //dis= new DataInputStream(client.getInputStream());
            //response=dis.readUTF();
           response = bufferedReader.toString();
            client.getInputStream();

          // client.shutdownInput();
           // client.shutdownOutput();
           client.close();

        } 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.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);
    }
}

这是我在客户端创建的新 Activity 的代码。

 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.widget.TextView;


 public class respond extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_respond);
    Intent intent=getIntent();
    String message = intent.getStringExtra(MainActivity.Extra_message);
    TextView response;
    response= (TextView) findViewById(R.id.textView1);
    response.setText(message);
}

@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_respond, 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);
   }
}

这是java中的服务器代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.DataOutputStream;





public class Server {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
    private static PrintWriter printwriter ;
    static DataOutputStream dos;


    public static void main(String[] args) {
        String w="Hello World";


        try {
        serverSocket = new ServerSocket(4446); // Server socket

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

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

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



                            dos=new DataOutputStream(clientSocket.getOutputStream());

                            dos.writeUTF(w);
                            clientSocket.close();
                            System.out.println(dos);


                            inputStreamReader.close();



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

            }

}

最佳答案

此示例向服务器(wlan 中的 PC)发送一条消息, 然后将消息从服​​务器返回到手机,并相应地更改文本。

将服务器的IP地址更改为您在wlan中的电脑地址, 确保首先启动服务器,然后启动手机应用程序,位于该无线局域网中

服务器:

public class ChatServer implements Runnable{

private Socket socket = null;
private ServerSocket server = null;
private Thread       thread = null;

private DataInputStream streamIn  =  null;
private DataOutputStream streamOut = null;


int port;
boolean done ;

public ChatServer(){
    port = 6668;
    try{
        System.out.println("Gewählter Port: " + port + ", bitte warte...");
        server = new ServerSocket(port);
        System.out.println("Server gestartet: " + server);
        start();
    }
    catch(IOException ioe)
    {
        System.out.println(ioe);
    }
}
public void start(){
    if (thread == null){
        thread = new Thread(this);
        thread.start();
    }
}

public void run(){
    while (thread != null){
        try{
            System.out.println("waiting for Client ...");
            socket = server.accept();
            System.out.println("Client accepted: " + socket + " IP: "+ socket.getInetAddress());
            System.out.println("connecting ...");
            open();
            done = false;

            while (!done){
                try{
                    String line = streamIn.readUTF();
                    System.out.println(line);
                    send("Server recieved :"+line);
                    done = line.equals(".bye");
                }
                catch(IOException ioe){
                    done = true;
                    ioe.printStackTrace();
                }
            }
            close();
        }
        catch(IOException ie){
            System.out.println("Acceptance Error: " + ie);
        }
    }
}
public void send(String msg)
{
    try
    {
        if(msg != null) {
            streamOut.writeUTF(msg);
            streamOut.flush();
        }
    }
    catch(IOException ioe)
    {
        ioe.printStackTrace();
    }
}
public void open() throws IOException{
    streamIn  = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    streamOut = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException{
    if (socket != null)    socket.close();
    if (streamIn != null)  streamIn.close();
    if (streamOut != null)  streamOut.close();

}
@SuppressWarnings("deprecation")
public void stop(){
    if (thread != null){
        thread.stop();
        thread = null;
    }
}


}

客户:

public class MainActivity extends Activity implements Runnable{

EditText textUnten;
Button button;
ChatProzKlasse chat;
public static String puffer;
public static String messages;
public static TextView textMitte;
Thread thread;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textMitte = (TextView) findViewById (R.id.textMitteID);
    textUnten = (EditText) findViewById (R.id.textUntenID);
    button = (Button) findViewById(R.id.sendButton);

    messages = "";



    chat = new ChatProzKlasse();
    thread = new Thread(this);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chat.client.send(textUnten.getText().toString());
            textUnten.setText("");



        }
    });
    thread.start();


}

public  void setTextMitte(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            textMitte.setText(messages);
        }
        });


}
@Override
protected void onResume() {
    super.onResume();



}

@Override
public void run() {
    while(true) {
        setTextMitte();
        try {
            thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


}
public class ChatClient {

private Socket socket              = null;

private DataInputStream console    = null;
private DataOutputStream streamOut = null;
private DataInputStream streamIn = null;
public static boolean isconnected = false;

public ChatClient(String serverName, int serverPort){
    System.out.println("Verbindungsaufbau. Bitte warten ...");
    try{
        socket = new Socket(serverName, serverPort);
        Log.d("DEBUG", "Connected: " + socket);
        if(socket != null) {
            start();
        }
    }
    catch(UnknownHostException uhe){
        Log.d("DEBUG","Host unknown: " + uhe.getMessage());
    }
    catch(IOException ioe){
        Log.d("DEBUG","Unexpected exception: " + ioe.getMessage());
    }

}

public void start() throws IOException
{
    console   = new DataInputStream(System.in);
    streamOut = new DataOutputStream(socket.getOutputStream());
    isconnected = true;

}

public void stop(){
    try{
        if (console   != null)  console.close();
        if (streamOut != null)  streamOut.close();
        if (socket    != null)  socket.close();
    }
    catch(IOException ioe){
        System.out.println("Error closing ...");
    }
}
public void open() throws IOException{
    streamIn  = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException{
    if (socket != null)    socket.close();
    if (console != null)  console.close();
}

public void send(String msg)
{
    try
    {
        if(msg != null) {
            streamOut.writeUTF(msg);
            streamOut.flush();
        }
    }
    catch(IOException ioe)
    {
        Log.d("DEBUG","Sending error: " + ioe.getMessage());
    }
}

public void recieve(){
    try{
        open();
        boolean done = false;

        while (!done){
            try{
                String line = streamIn.readUTF();
                if(!(line.equals(""))) {
                    MainActivity.messages =line;
                    MainActivity.puffer = line;
                }
                System.out.println(" " + line);
                done = line.equals(".bye");
            }
            catch(IOException ioe){
                done = true;
                ioe.printStackTrace();
            }
        }
        close();
    }
    catch(IOException ie){
        System.out.println("Acceptance Error: " + ie);
    }
}



}



public class ChatProzKlasse implements Runnable {
Thread thread;
ChatClient client;

public ChatProzKlasse(){
    thread = new Thread(this);
    thread.start();

}

@Override
public synchronized void run() {

    if(client == null) {
        try {
            System.out.println(" trying new Client");
            client = new ChatClient("192.168.1.111", 6668);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (client !=null){
        if(client != null && ChatClient.isconnected) {
            client.recieve();
        }
    }

}}

关于java - android客户端与java服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35052423/

相关文章:

java - 为什么我的后端应用程序未在Spring Boot中运行?

java - scala 反射在这种情况下无法工作

java - 无法导入 'com.google.android.maps'

java - ClassLoader 应该是线程安全的吗?

java - 写入 stdout,也像真正的终端一样打印提供的输入

java - 这个享元模式真的是享元模式吗?

android - UI 上不显示可绘制图像?

android - Gear VR - 你不是开发者

android - 如何安全地将android连接到mysql数据库

android - dagger hilt android中的ActivityRetainedComponent @ActivityRetainedScope和ActivityComponent @ActivityScoped有什么区别