I read the documentation, but it is not clear whats the difference between bind()
and connect()
methods.
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);
}
}
}
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.
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.
Connect is used by client to connect to listening server socket.
Finally accept is used by server socket when a client wants to connect to it while it was in the listening state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With