Android客户端没有收到消息(Android Client didn't get a message)

编程入门 行业动态 更新时间:2024-10-28 00:25:55
Android客户端没有收到消息(Android Client didn't get a message)

我是android和java编程的新手。 我正在编写服务器客户端连接。 我的PC应该是服务器,我的Android智能手机应该是客户端。 服务器运行良好。 我可以从客户端向服务器发送消息,但我无法从服务器向客户端发送消息。 当我这样做时,客户端会自行压缩和关闭。 我真的希望有人可以帮我解决我的大问题。

这是我的活动:

package com.example.sercerclient2zweidreidrei; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MyActivity extends Activity { Button btn; EditText textOut; TextView textIn; TextView problems; Button send; private TCPClient myTcpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText editText = (EditText) findViewById(R.id.editText); final TextView textIn = (TextView) findViewById(R.id.textin); Button send = (Button)findViewById(R.id.send_button); // connect to the server new connectTask().execute(""); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = editText.getText().toString(); //sends the message to the server if (myTcpClient != null) { myTcpClient.sendMessage(message); } } }); } public class connectTask extends AsyncTask<String,String,TCPClient> { @Override protected TCPClient doInBackground(String... message) { //we create a TCPClient object and myTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { @Override //here the messageReceived method is implemented public void messageReceived(String message) { //this method calls the onProgressUpdate publishProgress(message); } }); myTcpClient.run(); return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); //in the arrayList we don't add the message received from server //here i try to write the incomming message into a textVie textIn.setText(values[0]); } } }

这是我的TCPClient类:

package com.example.sercerclient2zweidreidrei; import android.util.Log; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class TCPClient { private String serverMessage; public static final String SERVERIP = "192.168.2.107"; //your computer IP address public static final int SERVERPORT = 4444; private OnMessageReceived mMessageListener = null; private boolean mRun = false; PrintWriter out; BufferedReader in; /** * constructor of the class. OnMessageReceived listens for the messages * received from server */ public TCPClient(OnMessageReceived listener) { mMessageListener = listener; } /** * Sends the message entered by client to the server * @param message text entered by client */ public void sendMessage(String message){ if (out != null && !out.checkError()) { out.println(message); out.flush(); } } public void stopClient() { mRun = false; } public void run() { mRun = true; try { // here you must put your computer's IP address. InetAddress serverAddr = InetAddress.getByName(SERVERIP); Log.e("TCP Client", "C: Connecting..."); //create a socket to make the connection with the server Socket socket = new Socket(serverAddr, SERVERPORT); try { //send the message to the server out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); Log.e("TCP Client", "C: Sent."); Log.e("TCP Client", "C:Done."); //receive the message which the server sends back in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //in this while the client listens for the messages send by the server while (mRun) { serverMessage = in.readLine(); if (serverMessage != null && mMessageListener != null) { //call the method messageReceived from MyActivity class mMessageListener.messageReceived(serverMessage); } serverMessage = null; } Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'"); } catch (Exception e) { Log.e("TCP", "S: Error", e); } finally { //the socket must be closed. It is not possible to reconnect to this socket //after it is closed, which means a new socket instance has to be created. socket.close(); } } catch (Exception e) { Log.e("TCP", "C:Error", e); } } /* * Declare the interface. The method messageReceived(String message must be * implemented in the MyActivity class at on asynckTask doInBackground */ public interface OnMessageReceived { public void messageReceived(String message); } }

最后在这里你可以看到我的main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MyActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="@string/Textausgabe" /> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="34dp" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/send_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/editText" android:layout_marginTop="26dp" android:text="@string/Senden" /> <TextView android:id="@+id/textin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:text="@string/EinkommenderText" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>

这是我的LogCat:

12-30 16:36:37.340:I / dalvikvm(548):threadid = 3:对信号3作出反应

12-30 16:36:37.560:I / dalvikvm(548):将堆栈跟踪写入'/data/anr/traces.txt'

12-30 16:36:37.740:I / dalvikvm(548):threadid = 3:对信号3作出反应

12-30 16:36:37.790:I / dalvikvm(548):将堆栈跟踪写入'/data/anr/traces.txt'

12-30 16:36:38.350:D / gralloc_goldfish(548):未检测到GPU仿真的仿真器。

12-30 16:36:38.630:I / dalvikvm(548):threadid = 3:对信号3作出反应

12-30 16:36:38.650:I / dalvikvm(548):将堆栈跟踪写入'/data/anr/traces.txt'

12-30 16:36:39.721:E / TCP客户端(548):C:正在连接...

12-30 16:36:39.981:E / TCP客户端(548):C:已发送。

12-30 16:36:39.990:E / TCP客户端(548):C:完成。

12-30 16:38:59.034:D / AndroidRuntime(548):关闭VM

12-30 16:38:59.034:W / dalvikvm(548):threadid = 1:线程退出,未捕获异常(group = 0x409c01f8)

12-30 16:38:59.051:E / AndroidRuntime(548):致命异常:主要

12-30 16:38:59.051:E / AndroidRuntime(548):java.lang.NullPointerException

12-30 16:38:59.051:E / AndroidRuntime(548):at com.example.sercerclient2zweidreidrei.MyActivity $ connectTask.onProgressUpdate(MyActivity.java:72)

12-30 16:38:59.051:E / AndroidRuntime(548):at com.example.sercerclient2zweidreidrei.MyActivity $ connectTask.onProgressUpdate(MyActivity.java:1)

12-30 16:38:59.051:E / AndroidRuntime(548):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:618)

12-30 16:38:59.051:E / AndroidRuntime(548):在android.os.Handler.dispatchMessage(Handler.java:99)

12-30 16:38:59.051:E / AndroidRuntime(548):在android.os.Looper.loop(Looper.java:137)

12-30 16:38:59.051:E / AndroidRuntime(548):在android.app.ActivityThread.main(ActivityThread.java:4424)

12-30 16:38:59.051:E / AndroidRuntime(548):at java.lang.reflect.Method.invokeNative(Native Method)

12-30 16:38:59.051:E / AndroidRuntime(548):at java.lang.reflect.Method.invoke(Method.java:511)

12-30 16:38:59.051:E / AndroidRuntime(548):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)

12-30 16:38:59.051:E / AndroidRuntime(548):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)

12-30 16:38:59.051:E / AndroidRuntime(548):at dalvik.system.NativeStart.main(Native Method)

12-30 16:38:59.752:I / dalvikvm(548):threadid = 3:对信号3作出反应

12-30 16:38:59.900:I / dalvikvm(548):将堆栈跟踪写入'/data/anr/traces.txt'

我希望你能找到我的错误。

i am pretty new to android and java programming. I am programming a server client connection. My PC shall be the server and my android smartphone shall be the client. The server works great. I can send a message from the client to the server, but I can't send a message from the server to the client. When i am doing this the client crushes and closes itself. I really hope that anybody can help me with my big issue.

Here is my Activity:

package com.example.sercerclient2zweidreidrei; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MyActivity extends Activity { Button btn; EditText textOut; TextView textIn; TextView problems; Button send; private TCPClient myTcpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText editText = (EditText) findViewById(R.id.editText); final TextView textIn = (TextView) findViewById(R.id.textin); Button send = (Button)findViewById(R.id.send_button); // connect to the server new connectTask().execute(""); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = editText.getText().toString(); //sends the message to the server if (myTcpClient != null) { myTcpClient.sendMessage(message); } } }); } public class connectTask extends AsyncTask<String,String,TCPClient> { @Override protected TCPClient doInBackground(String... message) { //we create a TCPClient object and myTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { @Override //here the messageReceived method is implemented public void messageReceived(String message) { //this method calls the onProgressUpdate publishProgress(message); } }); myTcpClient.run(); return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); //in the arrayList we don't add the message received from server //here i try to write the incomming message into a textVie textIn.setText(values[0]); } } }

and here is my TCPClient class:

package com.example.sercerclient2zweidreidrei; import android.util.Log; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class TCPClient { private String serverMessage; public static final String SERVERIP = "192.168.2.107"; //your computer IP address public static final int SERVERPORT = 4444; private OnMessageReceived mMessageListener = null; private boolean mRun = false; PrintWriter out; BufferedReader in; /** * constructor of the class. OnMessageReceived listens for the messages * received from server */ public TCPClient(OnMessageReceived listener) { mMessageListener = listener; } /** * Sends the message entered by client to the server * @param message text entered by client */ public void sendMessage(String message){ if (out != null && !out.checkError()) { out.println(message); out.flush(); } } public void stopClient() { mRun = false; } public void run() { mRun = true; try { // here you must put your computer's IP address. InetAddress serverAddr = InetAddress.getByName(SERVERIP); Log.e("TCP Client", "C: Connecting..."); //create a socket to make the connection with the server Socket socket = new Socket(serverAddr, SERVERPORT); try { //send the message to the server out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); Log.e("TCP Client", "C: Sent."); Log.e("TCP Client", "C:Done."); //receive the message which the server sends back in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //in this while the client listens for the messages send by the server while (mRun) { serverMessage = in.readLine(); if (serverMessage != null && mMessageListener != null) { //call the method messageReceived from MyActivity class mMessageListener.messageReceived(serverMessage); } serverMessage = null; } Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'"); } catch (Exception e) { Log.e("TCP", "S: Error", e); } finally { //the socket must be closed. It is not possible to reconnect to this socket //after it is closed, which means a new socket instance has to be created. socket.close(); } } catch (Exception e) { Log.e("TCP", "C:Error", e); } } /* * Declare the interface. The method messageReceived(String message must be * implemented in the MyActivity class at on asynckTask doInBackground */ public interface OnMessageReceived { public void messageReceived(String message); } }

Finally here you can see my main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MyActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="@string/Textausgabe" /> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="34dp" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/send_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/editText" android:layout_marginTop="26dp" android:text="@string/Senden" /> <TextView android:id="@+id/textin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:text="@string/EinkommenderText" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>

Here is my LogCat:

12-30 16:36:37.340: I/dalvikvm(548): threadid=3: reacting to signal 3

12-30 16:36:37.560: I/dalvikvm(548): Wrote stack traces to '/data/anr/traces.txt'

12-30 16:36:37.740: I/dalvikvm(548): threadid=3: reacting to signal 3

12-30 16:36:37.790: I/dalvikvm(548): Wrote stack traces to '/data/anr/traces.txt'

12-30 16:36:38.350: D/gralloc_goldfish(548): Emulator without GPU emulation detected.

12-30 16:36:38.630: I/dalvikvm(548): threadid=3: reacting to signal 3

12-30 16:36:38.650: I/dalvikvm(548): Wrote stack traces to '/data/anr/traces.txt'

12-30 16:36:39.721: E/TCP Client(548): C: Connecting...

12-30 16:36:39.981: E/TCP Client(548): C: Sent.

12-30 16:36:39.990: E/TCP Client(548): C:Done.

12-30 16:38:59.034: D/AndroidRuntime(548): Shutting down VM

12-30 16:38:59.034: W/dalvikvm(548): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)

12-30 16:38:59.051: E/AndroidRuntime(548): FATAL EXCEPTION: main

12-30 16:38:59.051: E/AndroidRuntime(548): java.lang.NullPointerException

12-30 16:38:59.051: E/AndroidRuntime(548): at com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:72)

12-30 16:38:59.051: E/AndroidRuntime(548): at com.example.sercerclient2zweidreidrei.MyActivity$connectTask.onProgressUpdate(MyActivity.java:1)

12-30 16:38:59.051: E/AndroidRuntime(548): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)

12-30 16:38:59.051: E/AndroidRuntime(548): at android.os.Handler.dispatchMessage(Handler.java:99)

12-30 16:38:59.051: E/AndroidRuntime(548): at android.os.Looper.loop(Looper.java:137)

12-30 16:38:59.051: E/AndroidRuntime(548): at android.app.ActivityThread.main(ActivityThread.java:4424)

12-30 16:38:59.051: E/AndroidRuntime(548): at java.lang.reflect.Method.invokeNative(Native Method)

12-30 16:38:59.051: E/AndroidRuntime(548): at java.lang.reflect.Method.invoke(Method.java:511)

12-30 16:38:59.051: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)

12-30 16:38:59.051: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)

12-30 16:38:59.051: E/AndroidRuntime(548): at dalvik.system.NativeStart.main(Native Method)

12-30 16:38:59.752: I/dalvikvm(548): threadid=3: reacting to signal 3

12-30 16:38:59.900: I/dalvikvm(548): Wrote stack traces to '/data/anr/traces.txt'

I hope you can find my mistake.

最满意答案

您在Activity中使用AsyncTask任务来建立TCP连接。 因此,一旦建立连接,就会发送消息并完成AsyncTask任务并关闭TCP连接。

您应该使用独立服务而不是活动来保持连接打开。

You use an AsyncTask task in an Activity to establish a TCP connection. So as soon as the connection is established the message is sent and your AsyncTask task finishes and you close the TCP connection.

You should use a stand-alone service instead of an Activity to keep the connection open.

更多推荐

本文发布于:2023-08-05 06:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   消息   Android   Client   message

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!