wg547308195
大师已去
2015-05-20 06:40

android模拟器与pc的相互通信

  • 模拟器与pc通讯
  • android

我现在再能实现模拟器联系pc,pc作为服务器被动的做出反应。不能实现pc发消息给模拟器。那要如何实现相互的通信呢

代码如下:

 package com.example.socket_android;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 测试Android客户端与PC服务器通过socket进行交互
 * 客户端:把用户输入的信息发送给服务器
 * @author Ameyume
 *
 */
public class MainActivity extends Activity {
    private static final String TAG = "Socket_Android";

    private EditText mEditText = null;
    private TextView tx1 = null;
    private Button mButton = null;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //强制占用ui
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        mButton = (Button)findViewById(R.id.button1);
        mEditText=(EditText)findViewById(R.id.editText1);
        //mEditText = (EditText)findViewById(R.id.editText1);
        tx1 = (TextView)findViewById(R.id.textView1);

        mButton.setOnClickListener(new OnClickListener() {

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


                setTitle("测试Socket连接");
                Socket socket = null;

                try {
                    /* 指定Server的IP地址,此地址为局域网地址,如果是使用WIFI上网,则为PC机的WIFI IP地址
                     * 在ipconfig查看到的IP地址如下:
                     * Ethernet adapter 无线网络连接:
                     * Connection-specific DNS Suffix  . : IP Address. . . . . . . . . . . . : 192.168.1.100
                     */
                    InetAddress serverAddr = InetAddress.getByName("192.168.1.225");// TCPServer.SERVERIP
                    Log.d("TCP", "C: Connecting...");

                    // 应用Server的IP和端口建立Socket对象
                    socket = new Socket(serverAddr, 51706);
                    String message = "---Test_Socket_Android---";  

                    Log.d("TCP", "C: Sending: '" + message + "'");  

                    // 将信息通过这个对象来发送给Server  
                    PrintWriter out = new PrintWriter(new BufferedWriter(  
                            new OutputStreamWriter(socket.getOutputStream())),  
                            true);  

                    // 把用户输入的内容发送给server
                    String toServer = mEditText.getText().toString();
                    Log.d(TAG, "To server:'" + toServer + "'");
                    out.println(toServer);
                    out.flush();  


                    // 接收服务器信息  
                    BufferedReader in = new BufferedReader(  
                                new InputStreamReader(socket.getInputStream()));  
                    // 得到服务器信息  
                    String msg = in.readLine();
                    Log.d(TAG, "From server:'" + msg + "'");
                    // 在页面上进行显示  
                    tx1.setText(msg);  
                } catch(UnknownHostException e) {
                    //Log.e(TAG, "192.168.1.100 is unkown server!");
                    Log.e(TAG, "192.168.1.225 is unkown server!");
                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        socket.close();
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        });
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#aacccc"
    tools:context="com.example.socket_android.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="40dp"
        android:layout_toRightOf="@+id/textView4"   
        android:background="#aaccff" 
        android:text="发送" />

    <TextView
        android:id="@+id/textView1"
        android:background="#aaccff"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
      />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"

        android:layout_marginTop="28dp"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_alignRight="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginRight="22dp"
        android:layout_marginTop="74dp"
        android:gravity="center"
        android:text="指令" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="60dp"
        android:layout_height="20dp"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="25dp"
        android:text="返回结果:" />

    <EditText
        android:id="@+id/editText1"
        android:background="#aaccff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignRight="@+id/textView1"
        android:layout_toRightOf="@+id/textView4"
        android:ems="10" />

</RelativeLayout> 
 //package Project1;

///**
// * Class1 的摘要说明。
// */
//public class Class1
//{
//    public Class1()
//    {
//        //
//        // TODO: 在此处添加构造函数逻辑
//        //
//    }
//}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 测试Android客户端与PC服务器通过socket进行交互
 * 服务器端:接收客户端的信息并回送给客户
 * @author Ameyume
 *
 */
public class Server implements Runnable
{
    //public static final String SERVERIP = "192.168.1.100";
    public static final String SERVERIP = "192.168.1.225";
    public static final int SERVERPORT = 51706;

    public void run()
    {
        try
        {
            System.out.println("S: Connecting...");

            ServerSocket serverSocket = new ServerSocket(SERVERPORT);

            while (true)
            {
                // 等待接受客户端请求 
                Socket client = serverSocket.accept();

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

                try
                {
                    // 接受客户端信息
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(client.getInputStream()));

                    // 发送给客户端的消息 
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(client.getOutputStream())), true);

                    System.out.println("S: 111111");
                    String str = in.readLine(); // 读取客户端的信息
                    int j;

                    if (str.equals("a"))
                    {
                        j = 1;
                    }
                    else if (str.equals("b"))
                    {
                        j = 2;
                    }
                    else if(str.equals ("1"))
                    {
                        j = 3;
                    }
                    else
                    {
                        j=4;
                    }




                    switch (j)
                    {
                        case 1:
                            str = "a1";
                            break;
                        case 2:
                            str = "a2"; break;
                        case 3:
                            str = "a3"; break;
                        case 4:
                            str = "a4"; break;
                        case 5:
                            str = "a5"; break;
                        case 6:
                            str = "a6"; break;

                    }



                    System.out.println("S: 222222");
                    if (str != null)
                    {
                        // 设置返回信息,把从客户端接收的信息再返回给客户端
                        out.println("You sent to server message is:" + str);
                        out.flush();

                        // 把客户端发送的信息保存到文件中
                        File file = new File("C://android.txt");
                        FileOutputStream fops = new FileOutputStream(file);
                        byte[] b = str.getBytes();
                        for (int i = 0; i < b.length; i++)
                        {
                            fops.write(b[i]);
                        }
                        System.out.println("S: Received: '" + str + "'");
                    }
                    else
                    {
                        System.out.println("Not receiver anything from client!");
                    }
                }
                catch (Exception e)
                {
                    System.out.println("S: Error 1");
                    e.printStackTrace();
                }
                finally
                {
                    client.close();
                    System.out.println("S: Done.");
                }
            }
        }
        catch (Exception e)
        {
            System.out.println("S: Error 2");
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        Thread desktopServerThread = new Thread(new Server());
        desktopServerThread.start();

    }
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答