Reputation: 231
I am trying to implement a server client program to send message in Android.Can you please say me what are the errors in my code and how to rectify them? The server is running fine but the client program has one error.
This is the server code and this is running fine.
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();
}
}
}
}
}
The Client Code :
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");
}};
}
The Log is :
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)
I read that we cannot implement the networking thread in the UI thread.That is why I am using the AsyncTask thread.But even then I get the NetworkOnMainThread Exception.Please say me the errors in my program and how to rectify them.
Upvotes: 1
Views: 936
Reputation: 29199
you are doing textIn.setText(dataInputStream.readUTF());
in doInBackground() method. While, doInBackground should contain only operations which are not part of event thread, so, use
publishProgress(param); to achive this.
Upvotes: 0
Reputation: 265
That is why I am using the AsyncTask thread.But even then I get the NetworkOnMainThread Exception.
Actually you are not.You need to call execute() instead of calling doInBackground() directly, otherwise you're not using any of the plumbing provided by the AsyncTask, and you're just calling the method directly in the UI thread.
Upvotes: 2