erlang+android

创建server.erl
-module(server).
-export([start/0,start/1,process/1]).
-define(defPort, 8888).

start() -> start(?defPort).

start(Port) ->
  case gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}]) of
    {ok, LSock} -> server_loop(LSock);
    {error, Reason} -> exit({Port,Reason})
  end.

%% main server loop - wait for next connection, spawn child to process it
server_loop(LSock) ->
  case gen_tcp:accept(LSock) of
    {ok, Sock} ->
      spawn(?MODULE,process,[Sock]),
      server_loop(LSock);
    {error, Reason} ->
      exit({accept,Reason})
  end.

%% process current connection
process(Sock) ->
  Req = do_recv(Sock),
  io:format("~p~n", [Req]),
  {ok, D, []} = rfc4627:decode(Req),
  {obj, [{"name", _Name}, {"age", Age}]} = D,
  Name = binary_to_list(_Name),
  io:format("Name: ~p, Age: ~p~n", [Name, Age]),
  Resp = rfc4627:encode({obj, [{"name", 'Hideto2'}, {"age", 24}]}),
  do_send(Sock,Resp),
  gen_tcp:close(Sock).

%% send a line of text to the socket
do_send(Sock,Msg) ->
  case gen_tcp:send(Sock, Msg) of
    ok -> ok;
    {error, Reason} -> exit(Reason)
  end.

%% receive data from the socket
do_recv(Sock) ->
  case gen_tcp:recv(Sock, 0) of
    {ok, Bin} -> binary_to_list(Bin);
    {error, closed} -> exit(closed);
    {error, Reason} -> exit(Reason)
  end.

创建android项目
package com.test;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
	String strJson = "26";
	Thread thread;
	private Map<String, String> handlerMap = new HashMap<String, String>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		thread = new ThreadLoadData();
		thread.start();
	}

	// 点击搜索按钮后进入数据的加载
	class ThreadLoadData extends Thread { // 一个线程变量只能用一次,所以要执行相同的动作时就必须定义一个Thread类而不是一个Thread变量
		@Override
		public void run() {
			try {
				// 联网下载指定数量的数据
				Socket socket = new Socket("192.168.1.201", 8888);
				// JSONObject json = new JSONObject();

				OutputStreamWriter osw = new OutputStreamWriter(socket
						.getOutputStream());

				BufferedWriter writer = new BufferedWriter(osw);
				System.out.println("true");
				JSONObject param = new JSONObject();
				param.put("yuky", strJson.replace("\n", " "));

				System.out.println("true--->" + param.toString());
				writer.write(param.toString());
				writer.flush();
			} catch (Exception ex) {
				// this.destroy();
				System.out.println("ERR-->" + ex.getMessage());
			}
		}
	}

	public JSONObject getJSON() throws JSONException {
		return new JSONObject(strJson);
	}
}


启动服务器
c(server).
server:start().

启动android访问服务器。

服务器接收到:
"{\"yuky\":\"26\"}"

你可能感兴趣的:(android)