本文介绍了DatagramSocket类的bind()和connect()的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读文档,但目前尚不清楚什么之间的差异绑定()连接()的方法。

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.

连接()使插座做出的连接以一个地址/端口由不同的插座服务。换句话说,它是使用客户端连接,以一台服务器。多个客户端可以连接到端口。 注意:连接()不需要使用UDP(数据报)套接字,只有TCP / IP使用。 UDP是一个广播协议,以及连接()甚至不要求一个插座侦听到另一端。

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.

像这样的东西(改编自文档和未经测试)应该发送和接收消息你好,萝卜!本身在端口12345:

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);
        }
    }
}

这篇关于DatagramSocket类的bind()和connect()的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:03