Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatagramSocket bind() and connect() difference?

I read the documentation, but it is not clear whats the difference between bind() and connect() methods.

like image 240
Fabricio Avatar asked Oct 17 '12 20:10

Fabricio


2 Answers

bind() causes the socket to listen for incoming requests on a particular interface/port. In other words, it's used by servers to respond to incoming requests. Only one socket can bind a port.

connect() causes the socket to make a connection to an address/port serviced by a different socket. In other words, it's used by clients to connect to a server. Multiple clients can connect to a port. NOTE: connect() is not required for use with UDP (datagram) sockets, only TCP/IP. UDP is a broadcast protocol, and connect() does not even require that a socket is listening to the other end.

Something like this (adapted from the docs and untested) should send and receive the message "Hello, turnip!" to itself on port 12345:

package
{
    import flash.events.DatagramSocketEvent;
    import flash.net.DatagramSocket;

    public class TestClass
    {
        private var serverSocket:DatagramSocket = new DatagramSocket();
        private var clientSocket:DatagramSocket = new DatagramSocket();

        public function TestClass():void
        {
            this.serverSocket.bind(12345, "127.0.0.1");
            this.serverSocket.addEventListener(DatagramSocketDataEvent.DATA, dataReceived);
            this.serverSocket.receive();

            send("Hello, turnip!");
        }

        public function sendData(message:String):void
        {
            var data:ByteArray = new ByteArray();
            data.writeUTFBytes(message);

            try
            {
                clientSocket.send(data, 0, 0, "127.0.0.1", 12345);
                trace("sending:  " + message);
            }
            catch (error:Error)
            {
                trace(error.message);
            }
        }

        private function dataReceived(e:DatagramSocketDataEvent):void
        {
            var data:String = e.data.readUTFBytes(e.data.bytesAvailable);
            trace("received: " + data);
        }
    }
}
like image 136
Scott A Avatar answered Sep 28 '22 02:09

Scott A


  1. Bind is used to allocate a particular port by system to a socket and no other process can use this particular port until the first process releases it.It's typically used in server side.

  2. Listening and binding are not same, listen puts the socket into listening state, in other words, the server socket is saying that I am listening to incoming client connections now.

  3. Connect is used by client to connect to listening server socket.

  4. Finally accept is used by server socket when a client wants to connect to it while it was in the listening state.

like image 45
java_doctor_101 Avatar answered Sep 28 '22 02:09

java_doctor_101