Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1706687
  • 博文数量: 607
  • 博客积分: 10031
  • 博客等级: 上将
  • 技术积分: 6633
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-30 17:41
文章分类

全部博文(607)

文章存档

2011年(2)

2010年(15)

2009年(58)

2008年(172)

2007年(211)

2006年(149)

我的朋友

分类: Python/Ruby

2008-12-08 14:18:03

Erlang与Python间的socket通讯

更新时间:2008-01-25 作者:CSDN 来源:CSDN

本文关键词:

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()
    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()
    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)
阅读(822) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~