简体   繁体   English

Elix的TCP侦听器使用Erlang的gen_tcp模块

[英]TCP Listener on Elixir using Erlang's gen_tcp module

I am using the following code to create a TCP listener on elixir : 我使用以下代码在elixir上创建TCP侦听器:

defmodule KVServer do
use Application

@doc false
def start(_type, _args) do
  import Supervisor.Spec

  children = [
    supervisor(Task.Supervisor, [[name: KVServer.TaskSupervisor]]),
    worker(Task, [KVServer, :accept, [4040]])
  ]

  opts = [strategy: :one_for_one, name: KVServer.Supervisor]
  Supervisor.start_link(children, opts)
end

@doc """
  Starts accepting connections on the given `port`.
"""
def accept(port) do
  {:ok, socket} = :gen_tcp.listen(port,
                  [:binary, packet: :line, active: false, reuseaddr:     true])
  IO.puts "Accepting connections on port #{port}"
  loop_acceptor(socket)
end

defp loop_acceptor(socket) do
  {:ok, client} = :gen_tcp.accept(socket)
  {:ok, pid} = Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
  :ok = :gen_tcp.controlling_process(client, pid)
  loop_acceptor(socket)
end

defp serve(socket) do
  socket
  |> read_line()
  |> write_line(socket)

  serve(socket)
end

defp read_line(socket) do
  {:ok, data} = :gen_tcp.recv(socket, 0)
  data
end

defp write_line(line, socket) do
  :gen_tcp.send(socket, line)
end
end

It is taken from the following link: http://elixir-lang.org/getting-started/mix-otp/task-and-gen-tcp.html 它取自以下链接: http//elixir-lang.org/getting-started/mix-otp/task-and-gen-tcp.html

When I try to get data from my gps deveice (for which I am writing this piece of code) using :gen_tcp.recv(socket,0), I get an error: {:error, reason} = :gen_tcp.recv(socket, 0) and the reason it showed is just "closed". 当我尝试使用:gen_tcp.recv(socket,0)从我的gps deveice(我正在编写这段代码)中获取数据时,我收到一个错误: {:error, reason} = :gen_tcp.recv(socket, 0)它显示的原因只是“关闭”。

However, the device is sending data, which I confirmed using a tcp packet sniffer (tcpflow). 但是,设备正在发送数据,我使用tcp数据包嗅探器(tcpflow)确认了该数据。

Also, when I try to send data using telnet as described in the tutorial above, it works fine. 此外,当我尝试使用上面的教程中描述的telnet发送数据时,它工作正常。

Any help would be highly appreciated. 任何帮助将受到高度赞赏。

I was finally able to figure it out. 我终于弄清楚了。 Actually the device was sending raw stream of data not lines of data. 实际上,该设备正在发送原始数据流而不是数据行。 So I had to change "packet: :line" parameter in :gen_tcp.listen function to "packet: :raw". 所以我不得不将gen_tcp.listen函数中的“packet :: line”参数改为“packet :: raw”。

It was working on telnet because telnet sends lines of data (with line breaks). 它正在telnet上工作,因为telnet发送数据行(带换行符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM