Java Android客户端未正确向服务器发送消息
我正在为安卓设备上的客户端编写一个代码,向服务器发送消息,服务器应该会回复消息。布局由编辑文本字段、按钮和文本视图组成。当按下按钮时,消息应从编辑文本字段中提取并发送到服务器,当服务器收到消息时,它应回复一条消息,说明它已收到消息,然后客户端将接收该回复消息并将其写入文本视图。问题是,当我按两次on按钮时,消息会发送到服务器,然后当我第三次按时,服务器崩溃。如果您能帮助解决问题,我们将不胜感激。提前谢谢 这是我得到的logcat错误Java Android客户端未正确向服务器发送消息,java,android,sockets,Java,Android,Sockets,我正在为安卓设备上的客户端编写一个代码,向服务器发送消息,服务器应该会回复消息。布局由编辑文本字段、按钮和文本视图组成。当按下按钮时,消息应从编辑文本字段中提取并发送到服务器,当服务器收到消息时,它应回复一条消息,说明它已收到消息,然后客户端将接收该回复消息并将其写入文本视图。问题是,当我按两次on按钮时,消息会发送到服务器,然后当我第三次按时,服务器崩溃。如果您能帮助解决问题,我们将不胜感激。提前谢谢 这是我得到的logcat错误 02-04 04:18:38.065: I/Error51(3
02-04 04:18:38.065: I/Error51(32228): android.os.NetworkOnMainThreadException
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
<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>
更新
我尝试使用asyncTask,我不再收到Logcat错误,但现在服务器根本没有收到消息
以下是修改后的代码:
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);
}
}
}
package com.example.testclientandroid;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.PrintWriter;
导入java.net.InetAddress;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入android.app.Activity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
公共类MainActivity扩展了活动{
静态插座;
静态最终int服务器端口=50000;
静态最终字符串服务器\u IP=“192.168.0.105”;
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新线程(新ClientThread()).start();
按钮按钮=(按钮)findViewById(R.id.button1);
setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
//TODO自动生成的方法存根
新建CommunicationTask().execute();
}
});
}
私有静态类ClientThread实现可运行{
公开募捐{
试一试{
inetAddressServerAddr=InetAddress.getByName(服务器IP);
套接字=新套接字(serverAddr、SERVERPORT);
}捕获(未知后异常e){
Log.i(“Error64”,例如toString());
}捕获(IOE异常){
Log.i(“Error65”,例如toString());
}
}
}
私有类通信任务扩展异步任务{
@凌驾
受保护字符串doInBackground(无效…参数){
//TODO自动生成的方法存根
EditText EditText=(EditText)findViewById(R.id.editText1);
字符串结果;
试一试{
String str=editText.getText().toString();
PrintWriter out=新的PrintWriter(socket.getOutputStream(),true);
out.println(str);
BufferedReader in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
结果=in.readLine();
返回结果;
}捕获(未知后异常e){
Log.i(“Error47”,例如toString());
}捕获(IOE异常){
Log.i(“Error49”,例如toString());
}捕获(例外e){
Log.i(“Error51”,例如toString());
}
返回“错误”;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
TextView TextView=(TextView)findViewById(R.id.textView2);
setText(结果);
}
}
}
任何需要互联网的操作都应该在后台完成。尝试读取以删除此错误。尝试使用asynctask,它简单而容易。asynctask允许正确而容易地使用UI线程。此类允许在UI线程上执行后台操作和发布结果,而无需操纵线程和/或处理程序
这里有一个例子
私有类DownloadFilesTask扩展了AsyncTask{
受保护的长doInBackground(URL…URL){
int count=url.length;
长totalSize=0;
for(int i=0;i}您是否也可以发布Logcat错误…Logcat错误02-04 04:18:38.065:I/Error51(32228):android.os.NetworkOnMainThreadException此错误表示您正在使用主线程连接并联系服务器。。。你需要使用线程(更好的AsyncTask)我只是不知道你在哪里调用
服务器类
?不,服务器类是PC上的服务器应用程序,它不是android应用程序的一部分。我使用AsyncTask,但现在服务器甚至不会收到消息,我编辑了问题并添加了修改过的代码你知道怎么了吗?我使用了asyncTask,但现在服务器甚至没有收到消息,我编辑了问题并添加了修改过的代码你知道怎么了吗?我使用asyncTask,但现在服务器甚至没有收到消息,我已经添加了问题并添加了修改后的代码。你知道怎么了吗?
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());
}
}
}
}
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);
}
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}