简体   繁体   English

Android客户端未正确向服务器发送消息

[英]Android client not sending messages to server correctly

I'm writing a code for a client on an android device to send messages to a server and the server is supposed to reply to it. 我正在为Android设备上的客户端编写代码,以将消息发送到服务器,并且服务器应该对此进行回复。 the layout is composed of an edit text field, a button and a text view. 布局由一个编辑文本字段,一个按钮和一个文本视图组成。 When the button is pressed the message should be taken from the edit text field and sent to the server, when the server receives the message it should reply with a message stating that it has received it and then that reply message is to be received by the client and written on the text view. 当按下按钮时,该消息应从编辑文本字段中获取并发送到服务器,当服务器接收到该消息时,服务器应回复一条消息,指出已收到该消息,然后该消息将被服务器接收。客户端并写在文本视图上。 The problem is that the message is sent to the server when I press on button twice and then when I press the third time the server crashes. 问题是,当我两次按下按钮时,然后当我第三次按下服务器崩溃时,消息将发送到服务器。 Any help on what's the problem would really be appreciated. 对此问题的任何帮助将不胜感激。 Thanks in advance. 提前致谢。

This is the logcat error that I get 这是我得到的logcat错误

02-04 04:18:38.065: I/Error51(32228): android.os.NetworkOnMainThreadException

MainActivity.java MainActivity.java

package com.example.testclientandroid;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    static Socket socket;
    static final int SERVERPORT = 50000;
    static final String SERVER_IP = "192.168.0.105";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();

        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText editText = (EditText) findViewById(R.id.editText1);
                TextView textView = (TextView) findViewById(R.id.textView2);
                try {
                    String str = editText.getText().toString();

                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    out.println(str);

                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    textView.setText(in.readLine());

                } catch (UnknownHostException e) {
                    Log.i("Error47", e.toString());
                } catch (IOException e) {
                    Log.i("Error49", e.toString());
                } catch (Exception e) {
                    Log.i("Error51", e.toString());
                }
            }
        });
    }

    private static class ClientThread implements Runnable {

        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e) {
                Log.i("Error64", e.toString());
            } catch (IOException e) {
                Log.i("Error65", e.toString());
            }
        }

    }
}

activity_main.xml activity_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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        android:text="Send" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="53dp"
        android:text="Response:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1" />

</RelativeLayout>

Android Manifest.xml Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testclientandroid"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testclientandroid.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ServerClass.java ServerClass.java

package mainPackage;
//Server
import java.net.*;
import java.io.*;

public class ServerClass
{

    static final int PORTNUMBER = 50000;

    public static void main(String[] args) throws IOException
    {
        new Thread(new ServerThread()).start();
    }

    public static class ServerThread implements Runnable {

        ServerSocket serverSocket;
        Socket clientSocket;
        public void run() {
            try {
                serverSocket = new ServerSocket(PORTNUMBER);
                clientSocket = serverSocket.accept();
                new Thread(new CommunicationThread(clientSocket)).start();

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static class CommunicationThread implements Runnable {

        Socket socket;
        BufferedReader in;
        PrintWriter out;

        public CommunicationThread(Socket clientSocket) {

            socket = clientSocket;

            try {

                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //out = new PrintWriter(clientSocket.getOutputStream(), true); 
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public void run() {
            try {

                while(in.readLine() != null)
                {
                    System.out.println(in.readLine());
                    out.println(in.readLine() + " Received");
                }

            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    }
}

Update I tried using asyncTask, I don't get a Logcat error anymore but now the server doesn't receive the message at all, 我尝试使用asyncTask进行更新,我再也没有收到Logcat错误,但现在服务器根本没有收到消息,

Here's the modified code: 这是修改后的代码:

package com.example.testclientandroid;

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

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    static Socket socket;
    static final int SERVERPORT = 50000;
    static final String SERVER_IP = "192.168.0.105";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();

        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                new CommunicationTask().execute();
            }
        });
    }

    private static class ClientThread implements Runnable {

        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e) {
                Log.i("Error64", e.toString());
            } catch (IOException e) {
                Log.i("Error65", e.toString());
            }
        }
    }

    private class CommunicationTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            EditText editText = (EditText) findViewById(R.id.editText1);
            String result;
            try {
                String str = editText.getText().toString();

                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                out.println(str);

                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                result = in.readLine();
                return result;
            } catch (UnknownHostException e) {
                Log.i("Error47", e.toString());
            } catch (IOException e) {
                Log.i("Error49", e.toString());
            } catch (Exception e) {
                Log.i("Error51", e.toString());
            }
            return "Error";
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            TextView textView = (TextView) findViewById(R.id.textView2);
            textView.setText(result);
        }   
    }
}

Any operation that needs internet should be done on background. 任何需要互联网的操作都应在后台进行。 Try to read Asynctask to remove this error. 尝试阅读Asynctask以消除此错误。

Try to use asynctask , its simple and easier.AsyncTask enables proper and easy use of the UI thread. 尝试使用简单易用的asynctask.AsyncTask支持正确轻松地使用UI线程。 This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. 此类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

Here is an example private class DownloadFilesTask extends AsyncTask { protected Long doInBackground(URL... urls) { int count = urls.length; 这是一个私有类DownloadFilesTask扩展AsyncTask的示例{protected Long doInBackground(URL ... urls){int count = urls.length; long totalSize = 0; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); for(int i = 0; i <count; i ++){totalSize + = Downloader.downloadFile(urls [i]); publishProgress((int) ((i / (float) count) * 100)); publishProgress((int)(((i /(float)count)* 100)); // Escape early if cancel() is called if (isCancelled()) break; //如果(isCancelled())中断,则在调用cancel()时提前退出; } return totalSize; } return totalSize; } }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM