`
hideto
  • 浏览: 2652870 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Erlang和Ruby的Socket通讯

阅读更多
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),
  Resp = "Hello, " ++ Req ++ "!",
  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.


client.rb
require 'socket'

client = TCPSocket.open('localhost', 8888)
client.send("hideto", 0)
puts client.readlines
client.close


Erlang服务器编译运行:
Eshell > c(server.erl).
Eshell > server:start().


Ruby客户端解释运行:
> ruby client.rb
Hello, hideto!


分享到:
评论
1 楼 yuky1327 2011-10-11  
ruby实现也太简单了~~~
我想服务端用erlang,客户端用android调用。应该实现的原理也是一样吧?楼主有空给下意见,谢谢。

相关推荐

Global site tag (gtag.js) - Google Analytics