Я пытаюсь внедрить серверную клиентскую программу для отправки сообщения в Android. Можете ли вы сказать мне, какие ошибки в моем коде и как их исправить? Сервер работает нормально, но в клиентской программе есть одна ошибка.
Это код сервера, и он работает нормально.
package com.app.MyServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MyServer extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
@Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
Log.v("SErver ",ss.toString());
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
Log.v("Message ",m.toString());
m.what = MSG_ID;
try {
if (s == null && ss!=null)
{
s = ss.accept();
Log.v("Drrr","It is not null");
}
else
Log.v("The thing is ", "ss is null");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
Log.v("Error ",e.toString());
e.printStackTrace();
}
}
}
}
}
Код клиента:
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
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.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
protected class connect extends AsyncTask<String,DataInputStream,String>
{
@Override
protected void onPreExecute()
{
Log.i( "makemachine", "onPreExecute()" );
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.0.2.2", 5000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
publishProgress(dataInputStream);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (socket != null)
{
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
super.onPreExecute();
}
protected void onProgressUpdate(DataInputStream... dataInputStream) {
Log.v("The mesage length is ",dataInputStream.toString());
textIn.setText(dataInputStream.toString());
}
@Override
protected void onPostExecute( String result )
{
super.onPostExecute(result);
Log.i( "connected", "onPostExecute(): " + result );
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0)
{
Log.v("Sending the message ","to the server");
}};
}
Журнал:
02-06 01:55:31.421: E/AndroidRuntime(582): FATAL EXCEPTION: main
02-06 01:55:31.421: E/AndroidRuntime(582): android.os.NetworkOnMainThreadException
02-06 01:55:31.421: E/AndroidRuntime(582): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
02-06 01:55:31.421: E/AndroidRuntime(582): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
02-06 01:55:31.421: E/AndroidRuntime(582): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-06 01:55:31.421: E/AndroidRuntime(582): at libcore.io.IoBridge.connect(IoBridge.java:112)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.Socket.startupSocket(Socket.java:566)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.Socket.tryAllAddresses(Socket.java:127)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.Socket.<init>(Socket.java:177)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.net.Socket.<init>(Socket.java:149)
02-06 01:55:31.421: E/AndroidRuntime(582): at com.exercise.AndroidClient.AndroidClient$1.onClick(AndroidClient.java:45)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.view.View.performClick(View.java:3511)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.view.View$PerformClick.run(View.java:14105)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.os.Handler.handleCallback(Handler.java:605)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.os.Handler.dispatchMessage(Handler.java:92)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.os.Looper.loop(Looper.java:137)
02-06 01:55:31.421: E/AndroidRuntime(582): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 01:55:31.421: E/AndroidRuntime(582): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 01:55:31.421: E/AndroidRuntime(582): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-06 01:55:31.421: E/AndroidRuntime(582): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-06 01:55:31.421: E/AndroidRuntime(582): at dalvik.system.NativeStart.main(Native Method)
Я прочитал, что мы не можем реализовать сетевой поток в потоке пользовательского интерфейса. Вот почему я использую поток AsyncTask. Но даже тогда я получаю исключение NetworkOnMainThread. Пожалуйста, скажите мне об ошибках в моей программе и как их исправить.