简体   繁体   中英

android socket programming:client server communication?

I'm trying to develop client-server communication using socket:

package com.exercise.AndroidClient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

//import com.app.Client.ClientActivity.ServerThread;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidClientActivity 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);
    /* Runnable showmessage=new Runnable()
     {

        @Override
        public void run() {
            // TODO Auto-generated method stub


        }

     };*/
     /*Thread thd=new Thread(new ServerThread());
        thd.start();*/
 buttonSend.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        DataOutputStream dataOutputStream = null;
        try {
             Socket socket = new Socket("192.168.1.9", 70);
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
         try {

                dataOutputStream.writeUTF(textOut.getText().toString());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    }
});
 Thread thd=new Thread(new ServerThread());
    thd.start();
    /*buttonSend.setOnClickListener(buttonSendOnClickListener)
 Button.OnClickListener buttonSendOnClickListener
 = new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
 // TODO Auto-generated method stub

}
 }  */
 }
          public class ServerThread implements Runnable{
              @Override
                public void run() {
                  Socket socket = null;
                  DataOutputStream dataOutputStream = null;
                  DataInputStream dataInputStream = null;
                  BufferedReader in=null;

                  try {
                   socket = new Socket("192.168.1.9", 70);
                   InputStream inputStream = socket.getInputStream(); 
                //   DataInputStream in1 = new DataInputStream(inputStream);
                   char chstr[]=new char[512];
                    //textIn.setText("rafa2");
                    // DataInputStream inq=new DataInputStream(new BufferedInputStream(inputStream));
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    textIn.setText("rafa1"+in.read(chstr));
                  // textIn.setText("ramla"+socket+inq.readUTF());
                  }catch (UnknownHostException e) {
                        System.err.println("Don't know about host: taranis.");
                        System.exit(1);
                    } catch (IOException e) {
                        System.err.println("Couldn't get I/O for "
                                           + "the connection to: taranis.");
                        System.exit(1);
                    }



                  // dataInputStream = new DataInputStream(socket.getInputStream());

                     //  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                /*     BufferedReader stdIn = null;
                    try {
                          socket = new Socket("192.168.110.49", 4023);
                        stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        textIn.append("gggg"+stdIn.readLine());
                        String userInput;
                        while ((userInput =stdIn.readLine()) != null) {
                               // out.println(userInput);
                              //  System.out.println("echo: " + in.readLine());
                                textIn.append("rafa");
                                textIn.append(userInput+stdIn.readLine());
                    }} catch (IOException e1) {
                        // TODO Auto-generated catch block

                        e1.printStackTrace();
                    }
                       String userInput = null;
                        /*textIn.append("rafa1");
                        try {
                            textIn.append("jjjj"+stdIn.readLine());
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }*/
                /*      try {
                            String userInput;
                            while ((userInput =in1.readLine()) != null) {
                               // out.println(userInput);
                              //  System.out.println("echo: " + in.readLine());
                                textIn.append("rafa");
                                textIn.append(userInput+in.readLine());

                            }

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }*/



              }
          }

}

Here my question: why is the client not receiving message from server? It comes force close. What's the error in the code? It's sending message correctly to server. I'm using "Hercules" software as server.

Here are the errors in logcat:

02-26 12:34:35.956: E/AndroidRuntime(679): FATAL EXCEPTION: Thread-8
02-26 12:34:35.956: E/AndroidRuntime(679): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.view.View.invalidate(View.java:5139)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.widget.TextView.checkForRelayout(TextView.java:5364)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.widget.TextView.setText(TextView.java:2688)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.widget.TextView.setText(TextView.java:2556)
02-26 12:34:35.956: E/AndroidRuntime(679):  at android.widget.TextView.setText(TextView.java:2531)
02-26 12:34:35.956: E/AndroidRuntime(679):  at com.exercise.AndroidClient.AndroidClientActivity$ServerThread.run(AndroidClientActivity.java:101)
02-26 12:34:35.956: E/AndroidRuntime(679):  at java.lang.Thread.run(Thread.java:1096)
02-26 12:34:36.426: W/IInputConnectionWrapper(679): showStatusIcon on inactive InputConnection

I've been looking at your code and I can tell you some tips/things that can be causing you problems.

  • First of all you are using Hercules. I don't know how Hercules is implemented, but you have to ensure that the server is sending you the data as you expect, same encoding, same time... this means that you have to use the appropiate method from the InputStreamReader , when you want to read.

  • Secondly, the CPU goes faster than any Internet connection, this means that you will have to wait until you have some data and do something like this:

while(socket.getInputStream().available()!=0){}

The method avilable() returns the estimated number of bytes that will be ready to read; even though you should only use this method to answer to the question "is there definitely data ready?".

I Hope, that this helps a little.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM