最近开始学习erlang, 发现其对分布式支持真是强大,比如在C++等语言中网络包的粘包问题,在erlang中通过设置scoket的{packet, N}属性就回默认将包长添加在发送包的前面;通过{active, true} 或者{active, false}就能设定网络IO的主动通知或被动收取;erlang服务端如下:
-module(server).
-export([start/1, loop/1]).
start(Port) ->
{ok, Listen} = gen_tcp:listen(Port, [binary, {active, true}, {packet,2}]),
{ok, Socket} = gen_tcp:accept(Listen),
loop(Socket).
loop(Socket) ->
receive
{tcp, Socket, Data} ->
io:format("Recv Pkg~p~n", [Data]),
gen_tcp:send(Socket, "Hello World!"),
loop(Socket)
end.
python客户端代码如下:
#!/usr/bin/env python
import socket
import struct
import time
if __name__ == '__main__':
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect(('localhost', 9999))
buffer = struct.pack('!H5s', 5, 'abcde')
socket.send(buffer[0:2])
time.sleep(5) #检查粘包,及erlang消息推送完整检验
socket.send(buffer[2:7])
r_buffer = socket.recv(100)
if len(r_buffer) > 2 :
print struct.unpack('!H', r_buffer[0:2])#打印erlang推送包的包头前置长度信息
print r_buffer