elixir socket
1.0.0
该库包装了gen_tcp
、 gen_udp
和gen_sctp
、 ssl
并实现了 websockets 和ocks。
在您的mix.exs
文件中
defp deps do
[
# ...
{:socket, "~> 0.3"},
# ...
]
end
然后运行mix deps.get
进行安装
defmodule HTTP do
def get ( uri ) when is_binary ( uri ) or is_list ( uri ) do
get ( URI . parse ( uri ) )
end
def get ( % URI { host: host , port: port , path: path } ) do
sock = Socket.TCP . connect! host , port , packet: :line
sock |> Socket.Stream . send! "GET #{ path || "/" } HTTP/1.1 r n Host: #{ host } r n r n "
[ _ , code , text ] = Regex . run ~r " HTTP/1.1 (.*?) (.*?) s *$ " , sock |> Socket.Stream . recv!
headers = headers ( [ ] , sock ) |> Enum . into ( % { } )
sock |> Socket . packet! :raw
body = sock |> Socket.Stream . recv! ( String . to_integer ( headers [ "Content-Length" ] ) )
{ { String . to_integer ( code ) , text } , headers , body }
end
defp headers ( acc , sock ) do
case sock |> Socket.Stream . recv! do
" r n " ->
acc
line ->
[ _ , name , value ] = Regex . run ~r / ^(.*?): s *(.*?) s *$ / , line
headers ( [ { name , value } | acc ] , sock )
end
end
end
socket = Socket.Web . connect! "echo.websocket.org"
socket |> Socket.Web . send! { :text , "test" }
socket |> Socket.Web . recv! # => {:text, "test"}
为了连接到 TLS websocket,请使用secure: true
选项:
socket = Socket.Web . connect! "echo.websocket.org" , secure: true
connect!
函数还接受其他参数,最值得注意的是path
参数,当 websocket 服务器端点存在于域下方的路径上时使用该参数。 “example.com/websocket”:
socket = Socket.Web . connect! "example.com" , path: "/websocket"
请注意,websocket 服务器发送 ping 消息。来自客户端的 pong 回复告诉服务器保持连接打开并发送更多数据。如果您的客户端没有发送 pong 回复,那么服务器将关闭连接。以下是如何获取所需数据并回复服务器 ping 的示例:
socket = Socket.Web . connect! "echo.websocket.org"
case socket |> Socket.Web . recv! do
{ :text , data } ->
# process data
{ :ping , _ } - >
socket |> Socket.Web . send! ( { :pong , "" } )
end
server = Socket.Web . listen! 80
client = server |> Socket.Web . accept!
# here you can verify if you want to accept the request or not, call
# `Socket.Web.close!` if you don't want to accept it, or else call
# `Socket.Web.accept!`
client |> Socket.Web . accept!
# echo the first message
client |> Socket.Web . send! ( client |> Socket.Web . recv! )