| CPyUG |
v0.9.2 071013
推荐使用FireFox获取最佳浏览体验! |
| Zoom.Quiet |
-module(eserver).
-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.
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)
import candygram as cg
class Thread:
...
# Create new thread.
counter = cg.spawn(Thread().run)
response = cg.Receiver()
response.addHandler((counter, int), lambda msg: msg[1], cg.Message)
# Tell thread to increment twice.
counter.send('increment')
counter.send('increment')
# Request thread's current value.
counter.send((cg.self(), 'value'))
# Print the response
print response.receive()
# Tell thread to increment one more time.
counter.send('increment')
counter.send((cg.self(), 'value'))
print response.receive()
counter.send('stop')