Java Android服务器客户端问题

Java Android服务器客户端问题,java,android,client,Java,Android,Client,我希望有人能帮我,我正在尝试创建一个基本应用程序,将设备的GPS坐标传输到服务器。我完全不懂socket编程(好吧,今年我在大学里讲了一些基本知识) 作为一个垫脚石,我正在遵循一个在线教程,它创建了服务器和android客户端,它被设计为将用户的输入发送到服务器,服务器在控制台上打印。 我已经非常熟悉如何设置服务器和客户端的基础,即打开端口等。问题是,当点击发送时,应用程序崩溃,在模拟器上测试时,显然存在问题,但我看不到 当我使用设备进行测试并点击send时,控制台上没有打印任何内容。我已经附加

我希望有人能帮我,我正在尝试创建一个基本应用程序,将设备的GPS坐标传输到服务器。我完全不懂socket编程(好吧,今年我在大学里讲了一些基本知识)

作为一个垫脚石,我正在遵循一个在线教程,它创建了服务器和android客户端,它被设计为将用户的输入发送到服务器,服务器在控制台上打印。 我已经非常熟悉如何设置服务器和客户端的基础,即打开端口等。问题是,当点击发送时,应用程序崩溃,在模拟器上测试时,显然存在问题,但我看不到

当我使用设备进行测试并点击send时,控制台上没有打印任何内容。我已经附加了下面的客户端和服务器代码,下面代码中的ip是用于模拟器的,我将其更改为我的设备ip,并使用它进行测试

*服务器*

public class Additional_Server {
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(2001); // Server socket
    } catch (IOException e) {
        System.out.println("Could not listen on port: 2001");
    }
    System.out.println("Server started. Listening to the port 2001");
    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");
        }
    }
}
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class TCPclient extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcpclient);
        textField = (EditText) findViewById(R.id.Msg); // reference to the text field
        button = (Button) findViewById(R.id.bSend); // 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
                try {
                    client = new Socket("127.0.0.1", 2001); // 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) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

*客户端*

public class Additional_Server {
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(2001); // Server socket
    } catch (IOException e) {
        System.out.println("Could not listen on port: 2001");
    }
    System.out.println("Server started. Listening to the port 2001");
    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");
        }
    }
}
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class TCPclient extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcpclient);
        textField = (EditText) findViewById(R.id.Msg); // reference to the text field
        button = (Button) findViewById(R.id.bSend); // 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
                try {
                    client = new Socket("127.0.0.1", 2001); // 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) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
我非常感谢任何指点、建议或帮助,因为我所看到的看起来都是正确的,但显然有些地方不正确。提前谢谢你

加里

我已经按照建议编辑了上面的代码,将其放入异步任务中,模拟器没有崩溃,但是,我仍然无法将任何打印输出到控制台。有人能帮忙吗?我在这里尝试,我只是不太习惯android,这是最好的学习方式

public class TCPclient extends Activity {

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tcpclient);

    textField = (EditText) findViewById(R.id.Msg);  // reference to the text field
    button = (Button) findViewById(R.id.bSend);     // reference to the send button
    messsage = textField.getText().toString();      // get the text message on the text field

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

        public void onClick(View v) {

            textField.setText(""); // Reset the text field to blank
            new commAsyncTask().execute();
        }

        class commAsyncTask extends AsyncTask<Void, Void, String> {

            @Override
            protected String doInBackground(Void... params) {
                // TODO Auto-generated method stub
                try {
                    client = new Socket("192.168.1.2", 2001); // connect to
                                                                // server
                    printwriter = new PrintWriter(client.getOutputStream());



                    printwriter.println(messsage); 
                    printwriter.flush();
                    printwriter.close();


                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

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

    });
}
公共类TCPclient扩展活动{
专用套接字客户端;
私人印刷作家;
私有编辑文本字段;
私人按钮;
私有字符串消息;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u tcpclient);
textField=(EditText)findViewById(R.id.Msg);//对文本字段的引用
button=(button)findViewById(R.id.bSend);//对发送按钮的引用
message=textField.getText().toString();//获取文本字段上的文本消息
//按钮按下事件侦听器
setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
textField.setText(“”;//将文本字段重置为空白
新建commAsyncTask().execute();
}
类commAsyncTask扩展了AsyncTask{
@凌驾
受保护字符串doInBackground(无效…参数){
//TODO自动生成的方法存根
试一试{
client=newsocket(“192.168.1.2”,2001);//连接到
//服务器
printwriter=新的printwriter(client.getOutputStream());
printwriter.println(消息);
printwriter.flush();
printwriter.close();
}捕获(未知后异常e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
}
}
});
}
}

所以,各位,外面有很多人比我聪明得多,非常感谢你们的帮助

tl dr-线程

基本上,在Android中,UI和代码都运行在线程上。因此,套接字代码阻止它运行UI部分,这导致Android操作系统认为应用程序没有响应(或类似的东西),因此它崩溃

编辑:
要修复此问题,请通过线程或异步任务或其他方式将sock放入另一个线程中

您不应在UI线程中执行此任务。创建一个单独的线程或在
AsynTask
中执行,谢谢大家的输入。我想我有一个想法,所以我在TCPclient中执行接口,创建一个单独的类,扩展ASyncTask,其中包含要执行的任务,然后在onClick方法中调用/执行该类?对不起,这对我来说是全新的!!有人能告诉我上面的说法是否正确吗?所以,如果我使用一个异步任务,它应该运行吗?@DJ-DOO,这就是我在一个示例中看到的用法。我个人打算使用一个线程,但我的应用程序基本上是不断地推送数据。我的应用程序也会这样做,它将不断地传输gps坐标,所以我可能最好使用另一个线程。这里没有人可以帮我吗?还是没有人会这么做?