Windows7上的AVD无法连接到Linux服务器

时间:2012-01-11 00:55:04

标签: java android sockets client-server

这与我之前的帖子“http://stackoverflow.com/questions/8788825/linux-udp-server-unreachable-from-window-7”有关,已经解决了。现在我转到将AVD连接到Linux服务器的原始工作。

我使用以下代码连接服务器

import java.net.*;

class UDPClient {

public final static int DesitnationPort = 9999;
private int mCounter;
private DatagramSocket mClientSocket;
private InetAddress mServerIPAddress;
private byte[] mDataBuffer;
private DatagramPacket mSendPacket;
private DatagramPacket mReceivePacket;

//Constructor
public UDPClient() {

    //Time to make the private data good one
    mCounter =1;
    try {
    mServerIPAddress = InetAddress.getByName("192.168.2.2");
    }
    catch(UnknownHostException e)
    {
        System.out.println("Host cannot be resolved :( ");
    }
    System.out.println("Host has been resolved The IP is valid one ");
    try {
    mClientSocket = new DatagramSocket();
    }
    catch(SocketException e)
    {
        System.out.println("Socket could not be created :( ==> " + e.getMessage());
    }
    System.out.println("Socket has been created ");
    String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
    mDataBuffer = temp.getBytes();
    mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
    System.out.println("Datagram has been made now ");
    System.out.println("Data ==>"+ mSendPacket.getData());
    System.out.println("Data ==>"+ mSendPacket.getPort());
    System.out.println("Data ==>"+ mSendPacket.getSocketAddress());
    System.out.println("Data ==>"+ mSendPacket.getLength());
}

public void SendDataToServer(){

    try {
            if(!mClientSocket.isClosed())   {

                String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
                mDataBuffer = temp.getBytes();
                mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);           
                mClientSocket.send(mSendPacket);
                System.out.println("Send the packet");
                mCounter++;
            }
            else    {

                System.out.println("Socket is closed");
            }
    }
    catch(Exception e)
    {
        System.out.println("Could not send the data :( ==> " + e.getMessage());
    }
}

public void ReceiveDataFromServer() {

    byte[] tembuff = new byte[1024];
    mReceivePacket = new DatagramPacket(tembuff, tembuff.length);
    try {
            if(!mClientSocket.isClosed())   {

                mClientSocket.receive(mReceivePacket);

            }
            else    {

                System.out.println("Socket is closed");
            }
    }
    catch(Exception e)
    {
        System.out.println("Could not Receive the data :( ");
        return;
    }
        String data = new String(mReceivePacket.getData());
        System.out.println(" Received the Data => " + data);
}
}

当我在java程序中使用这样的类时,这段代码很有效: -

class TryingWithClient {
public static void main(String a[]) {
    UDPClient mClient = new UDPClient();
    while(true) {
    System.out.println("While Starting");
    mClient.SendDataToServer();
    mClient.ReceiveDataFromServer();
    }
 }
}

当我在AVD项目中使用相同的代码时,我会在以下行获得Null指针异常: -

public void SendDataToServer(){     
    try {
        if(!mClientSocket.isClosed()){ //<==@ this call Null exception occurs

浏览互联网&amp; android开发网站我得出结论,我错过了我添加到AVD的GMS / GPS功能。我仍然无法得到任何关于此的线索。

这是我调用上述UDPClient的代码。

public class StreamingProjectActivity extends Activity {
/** Called when the activity is first created. */

//All buttons
//private static final String LOG_TAG = "StreamingTest";    
private StreamButton mStreamButton = null;
private UDPClient mClient= null;

class StreamButton extends Button {
    boolean mStartStreaming = true;

    OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {
            onStream(mStartStreaming);
            if (mStartStreaming) {
                setText("Stop Streaming");
            } else {
                setText("Start recording");
            }
            mStartStreaming = !mStartStreaming;
        }
    };

    public StreamButton(Context ctx) {
        super(ctx);
        setText("Start Streaming");
        setOnClickListener(clicker);
    }
}//class StreamButton Ends

@Override
public void onCreate(Bundle icicle) {
    try {

        mClient = new UDPClient();
        System.out.println("==========> Client created sucessfully :) <====== ");

        super.onCreate(icicle);

        LinearLayout ll = new LinearLayout(this);
        mStreamButton  = new StreamButton(this);
        ll.addView(mStreamButton,
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            0));

        setContentView(ll);
        System.out.println("Trying Step 2 now ");
}
catch(Exception e)
{
    System.out.println("Activity could not be launched :( ");   
}

}

//public StreamingTest()
public StreamingProjectActivity(){
System.out.println("Constructor ====>");
System.out.println("Constructor <====");
}//Constructor

private void onStream(boolean start) {
    if (start)
    {
        mClient.SendDataToServer();
        mClient.ReceiveDataFromServer();
        try
          {
            Thread.sleep(4000);  

          }catch (InterruptedException ie)
          {
              System.out.println(ie.getMessage());
          }

    }
 }//onStream
}

请帮助。

2 个答案:

答案 0 :(得分:1)

好的,首先:永远不要使用System.out.println("some msg " + e.getMessage());打印捕获的异常请为此使用Log.e(TAG, "my message", e);。所以你实际上会看到一个堆栈跟踪。

第二:我打赌这段代码会抛出一个错误(检查你是否在LogCat输出中看到了打印):

try {
    mClientSocket = new DatagramSocket();
} catch(SocketException e) {
    System.out.println("Socket could not be created :( ==> " + e.getMessage());
}

这是mClientSocket仍然可能为空的唯一原因。由于此调用可能出错,因此在检查套接字是否已关闭之前,应考虑检查null。

答案 1 :(得分:0)

我之前的解决方案中的问题是我正在混合使用GUI和网络操作在同一个线程中被称为“StricMode.ThreadPolicy”(虽然,我的问题只是行话中提到的部分)。

我得到了这些例外“android.os.NetworkOnMainThreadException&amp; android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)”,我只有在应用了WarrenFaith的建议(感谢Warren)之后才能解决这个问题。 / p>

仅在违反“StricMode”时抛出这些内容。

解决方案:只需将UI工作与网络分开即可。我必须为此编写以下代码:

enum ClientThreadStates {
eUndefined,
eStopped,
eRunning,
eIdle,
eSendToServer,
eReadFromServer
}

public class ClientThread extends Thread {

private UDPClient mClient= null;
private ClientThreadStates mStateOfTheThread = ClientThreadStates.eUndefined;
private static String mLOG_TAG; 

public ClientThread(String s){

    mLOG_TAG = s;
    mStateOfTheThread = ClientThreadStates.eStopped;
    mClient = new UDPClient(s);
    start();
}//constructor

public void SetState(ClientThreadStates paramState) {

    mStateOfTheThread = paramState;
}

public ClientThreadStates GetState() {

    return mStateOfTheThread;
}
private void Action(ClientThreadStates s) {

    synchronized(s) {

        switch(mStateOfTheThread)   {

        case eRunning: //fall
        case eIdle: break;
        case eSendToServer: mClient.SendDataToServer(); break;
        case eReadFromServer: mClient.ReceiveDataFromServer(); break;

        }
        try {
            mStateOfTheThread.wait();
        }
        catch( InterruptedException e ){
            Log.e(mLOG_TAG, "Got Exception at wait <==", e);
        }           

    }
}

public void run() {
    mStateOfTheThread = ClientThreadStates.eRunning;
    System.out.println("In Thread.run .. The State is " + mStateOfTheThread);
    while(ClientThreadStates.eStopped.compareTo(mStateOfTheThread) < 0){ //state >stopped

        Action(mStateOfTheThread);
    }//while

}//run
}//class ClientThread

最后在状态上的两个线程上同步,如下所示:

private void onStream(boolean start) {

    ClientThreadStates State = mClientThread.GetState();
    synchronized(State) {
        if (start)  {
            mClientThread.SetState(ClientThreadStates.eSendToServer);
        }
        else        {
            mClientThread.SetState(ClientThreadStates.eReadFromServer);
        }
        try {               
            State.notify();
        }
        catch( IllegalMonitorStateException  e ) {
                Log.e(LOG_TAG, "Got Exception @ notify <==", e);
        }        
    }
 }//onStream

}//StreamingProjectActivity

现在代码运行完美。

感谢。 Ashutosh说