(Android)用Socket的小例子

1,建立 PORT 映射

  Android模拟器启动后,要运行下个命令。使得模拟器和主机的 PORT 映射上。

telnet 127.0.0.1 5554
redir add tcp:8888:8888
 

2,放开权限

  在 AndroidManifest.xml 中加入下面一句。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
 

3,Android端的服务器程序片段如下。

  全部例子可从 google code 得到。

  https://javamp3player.googlecode.com/svn/AndroidHuaRongDao/

    public void run() {
        try {
            serverSocket = new ServerSocket(8888, 1024);
        }
        catch (IOException e) {
            e.printStackTrace();
            return;
        }

        InputStream in;
        while (!hasStopCmd) {
            try {
                client = serverSocket.accept();
                in = client.getInputStream();
            }
            catch (IOException e) {
                e.printStackTrace();
                return;
            }

            BufferedReader p = new BufferedReader(new InputStreamReader(in));

            while (!hasStopCmd) {
                TouchSimEvent event = new TouchSimEvent();
                try {
                    String str = p.readLine();
                    if (str == null) {
                        break;
                    }
                    event.set(str);
                }
                catch (IOException e) {
                    break;
                }

                for (TouchSimEventListener listener : listeners) {
                    listener.onTouchSimEvent(event);
                }
            }
        }
    }

 

4,PC端的客户程序如下

        try {
            serverAddr = InetAddress.getByName("127.0.0.1");
            socket = new Socket(serverAddr, 8888);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        TouchSimEvent event = new TouchSimEvent();
        event.setX(x);
        event.setY(y);
        event.setClick(click);
        try {
            if (!socket.isConnected()) {
                resetSocket();
            }

            PrintWriter p = new PrintWriter(socket.getOutputStream());
            p.println(event.get());
            p.flush();
        }
        catch (Exception e) {
        }

你可能感兴趣的:(android,xml,socket,SVN,Google)