[erlang-questions] Regarding gen_tcp:connect()

sameer pradhan <>
Wed Apr 8 08:36:58 CEST 2009


This is Sameer here.
I have used those lines in my code in client side of my program using
"localhost" instead of  IP address and its working fine.
For that 1st u have to run the server part  with gen_tcp:listen() and then
gen_tcp:accept().
Then u can try to connect that socket from client side.
If u need then i can send the appropriate code also.

Here is the Example---->
   for Socket---->

-module(socket11_server).
-export([start_server/0]).


start_server() ->
    {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 0},{reuseaddr,
true},{active,true}]),
    io:format("listen :~p~n",[Listen]),
    {ok, Socket} = gen_tcp:accept(Listen),
    io:format("socket :~p~n",[Socket]),
    gen_tcp:close(Listen),
    loop(Socket).
loop(Socket) ->
    receive
        {tcp, Socket, Bin} ->
            io:format("Server received binary = ~p~n",[Bin]),
            Str = binary_to_term(Bin),
            io:format("Server (unpacked)  ~p~n",[Str]),
            {address_book,''}!Str,
            loop(Socket);
        {tcp_closed, Socket} ->
            io:format("Server socket closed~n")
    end.




And For client ---->

       -module(socket11_client).
-export([client_eval/0,loop/1]).

client_eval() ->
        case gen_tcp:connect("localhost" , 2345,[binary,{packet, 0}]) of
        {ok,Socket}->
                io:format("Socket established~n"),
                io:format("socket :~p~n",[Socket]),
                register(client,spawn(?MODULE,loop,[Socket]));
        {error,Reason}->
                io:format("Error on connect: ~s~n",[Reason])
    end.



loop(Socket)->
    receive
        {client,stop}->
            io:format("client socket closed"),
            gen_tcp:close(Socket);
        {client,Data}->
            io:format("data is :::~p~n",[Data]),
            ok = gen_tcp:send(Socket, term_to_binary(Data)),
            io:format("~p~n",[Data]),
            loop(Socket);
            {tcp,Socket,Bin} ->
            io:format("Client received binary= ~p ~n ",[Bin]),
            Val = binary_to_term(Bin),
            io:format("Client result=~p~n",[Val]) ,
            loop(Socket)

    end.




-- 
Thanks & Regards
Sameer Prakash Pradhan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090408/425ef40e/attachment.html>


More information about the erlang-questions mailing list