免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3032 | 回复: 1

[其他] Erlang与Python间的socket通讯 [复制链接]

论坛徽章:
0
发表于 2006-10-02 23:24 |显示全部楼层
Erlang Server 端:
-module(eserver).
-author("hanzhupeng@gmail.com").
-export([startd/0, start/0,start/1,process/1]).
-define(defPort,2000).
startd() ->
    register(eserverp, spawn(?MODULE, start, [])).
   
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 world",
    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.
   
Python  Client端
import socket
HOST = 'localhost'    # The remote host
PORT = 6889              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4614/showart_179490.html

论坛徽章:
0
发表于 2010-01-13 23:27 |显示全部楼层
学习erlang中,很能锻炼人
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP