Glenda Guo Glenda Guo - 4 months ago 14
Android Question

android socket write error

I imagine that Android application as a client to send String to the server, PC based on Socket.

First, I write a small test program to see whether it can work by using a

EditText
and a send Button. PC can receive the string. Then I write a
MainActivity
to open the
SocketActivity
by button.onclick event. It can`t work.

My code..the socket part

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LightControlActivity extends Activity {
private Button mBtnSend;
private static final String TAG = "com.ldgforever.controlbywifi";
private String mIPAdress;
private int mPortNumber;
String ip="192.168.155.1";
int port=1920;
Socket socket = null;

private String mSendMsg = "test";

public static final String EXTRA_RECEIVE_IP =
"com.ldgforever.controlbywifi.receive_ip";
public static final String EXTRA_RECEIVE_PORT =
"com.ldgforever.controlbywifi.receive_port";

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.light_control);

ActionBar actionBar = getActionBar();
actionBar.setSubtitle("灯光管控");

mIPAdress = getIntent().getStringExtra(EXTRA_RECEIVE_IP);
mPortNumber = Integer.parseInt(getIntent()
.getStringExtra(EXTRA_RECEIVE_PORT));

mBtnSend = (Button)findViewById(R.id.send_data);
mBtnSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SetOnClick();
}
});
}
private void SetOnClick()
{
// TODO Auto-generated method stub
try {
if(!TextUtils.isEmpty(mSendMsg))
SendMsg(ip,port,mSendMsg);
else
{
Toast.makeText (LightControlActivity.this,"msg is EMPTY!!", Toast.LENGTH_LONG).show();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Toast.makeText(LightControlActivity.this,"!UnknownHostException!", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(LightControlActivity.this,"!IOException!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, "Exception");
Toast.makeText(LightControlActivity.this,"!Exception!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}

}

public void SendMsg(String ip,int port,String msg) throws UnknownHostException, IOException
{
try
{
socket = new Socket();
socket=new Socket(ip,port);
PrintWriter writer = new PrintWriter(new BufferedWriter
(new OutputStreamWriter(socket.getOutputStream())));
// BufferedWriter writer=new BufferedWriter(new OutputStreamWriter
// (socket.getOutputStream()));
// writer.write(msg);
writer.println(msg);
writer.flush();
writer.close();
socket.close();
}
catch(UnknownHostException e)
{
Log.e(TAG, "UnknownHostException");
e.printStackTrace();
} catch (IOException e)
{
Log.e(TAG, "IOException");
e.printStackTrace();
}
}


the Error occurred at SetOnClick() catch(Exception) I can`t find out the reason

My server code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPDesktopServer implements Runnable{


public static final String SERVERIP = "192.168.155.1";

public static final int SERVERPORT = 1920;


public void run() {

try {

System.out.println("S: Connecting...");

ServerSocket serverSocket = new ServerSocket(SERVERPORT);

while (true) {

Socket client = serverSocket.accept();

try {

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

String str = in.readLine();

System.out.println("S: Received: '" + str + "'");

} catch(Exception e) {

System.out.println("S: Error");

e.printStackTrace();

} finally {

client.close();

System.out.println("S: Done.");

}

}

} catch (Exception e) {

System.out.println("S: Error");

e.printStackTrace();
}
}

public static void main (String a[]) {

Thread ServerThread = new Thread(new TCPDesktopServer());

ServerThread.start();
}
}


I have added the Internet permission. …… ask for help……!

Answer

You can make use of AsyncTask to make socket call to server.

 private class SendData extends AsyncTask<Void, Void, Void> {

        String ip;
    int port;
    String msg;

    SendData(String ip,int port,String msg)
    {
        this.ip = ip;
        this.port = port;
        this.msg = msg;
    }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog


        }

        @Override
        protected Void doInBackground(Void... arg0) {
 try
{
  socket = new Socket();  
  socket=new Socket(ip,port); 
  PrintWriter writer = new PrintWriter(new BufferedWriter
          (new OutputStreamWriter(socket.getOutputStream())));
        //    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter
       //               (socket.getOutputStream()));
       //       writer.write(msg);
    writer.println(msg);
    writer.flush();
    writer.close();       
    socket.close();
}
catch(UnknownHostException e)
{
    Log.e(TAG, "UnknownHostException");
    e.printStackTrace();
} catch (IOException e) 
{
    Log.e(TAG, "IOException");
    e.printStackTrace();
}
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog

        }

    }

You can call this like, and simply pass IP, port and message to send data to server, and this will be done in background so, this should work:

 // Calling async task to send data
    new SendData (ip,port,mSendMsg).execute();