【问题标题】:How to connect to socket by TCP如何通过 TCP 连接到套接字
【发布时间】:2015-03-05 13:25:58
【问题描述】:

我在 OpenShift 上有 Erlang 的简单服务器,它创建套接字并等待新连接。服务器的本地 ip 是 127.10.206.129 并且服务器侦听 16000 端口。 我的服务器代码:

-module(chat).
-export ([start/0, wait_connect/2, handle/2]).

start() ->
{ok, ListenSocket} = gen_tcp:listen(16000, [binary, {ip,{127,10,206,129}}]),
wait_connect(ListenSocket, 0).

wait_connect(ListenSocket, Count) ->
io:format("~s~n", ["Wait..."]),
gen_tcp:accept(ListenSocket),
receive
    {tcp, _Socket, Packet} ->
        handle(Packet, Count),
        spawn(?MODULE, wait_connect, [ListenSocket, Count+1]);
    {tcp_error, _Socket, Reason} ->
        {error, Reason}
end.

我的客户代码:

-module(client).
-export ([client/2]).

client(Host, Data) ->
{ok, Socket} = gen_tcp:connect(Host, 16000, [binary]),
send(Socket, Data),
ok = gen_tcp:close(Socket).

send(Socket, <<Data/binary>>) ->
gen_tcp:send(Socket, Data).

服务器启动没有问题。我尝试在本地主机上运行客户端并出现错误(它尝试连接的时间比超时时间长:

 2> client:client("chat-bild.rhcloud.com", <<"Hello world!">>).
 ** exception error: no match of right hand side value {error,etimedout}
 in function  client:client/2 (client.erl, line 4)

我尝试了这种愚蠢的方式(虽然127.10.206.129是一个错误的ip,因为它是服务器本地ip):

 3> client:client({127,10,206,129}, <<"Hello world!">>).
 ** exception error: no match of right hand side value {error,econnrefused}
 in function  client:client/2 (client.erl, line 16)

gen_tcp:connect with url怎么做?

【问题讨论】:

    标签: sockets tcp erlang openshift


    【解决方案1】:

    在 openshift 上,只有 80、443、8000 和 8443 端口对外开放。您无法从本地工作站连接到 OpenShift 上的其他端口,除非您使用 rhc port-forward 命令,并且该命令仅适用于卡式磁带使用的已发布端口。

    【讨论】:

      【解决方案2】:

      您的listen 调用将监听接口限制为127.10.206.129,但从第二个客户端示例来看,您的客户端无法连接到该地址。尝试从您的listen 调用中删除{ip,{127,10,206,129}} 选项,以便您的服务器侦听所有可用的接口,或者找出服务器名称"chat-bild.rhcloud.com" 对应的接口并仅在该接口上侦听。

      【讨论】:

        猜你喜欢
        • 2017-11-23
        • 2012-02-28
        • 1970-01-01
        • 2011-03-13
        • 2015-05-26
        • 2011-08-31
        • 2023-03-21
        相关资源
        最近更新 更多