使用SOCKET通信的客户端,向服务器端发送数据。需要先BeginConnect,还是直接BeginSendTo就可以了?

解决方案 »

  1.   

    可以不需要BeginConnect()
    IPHostEntry lipa = Dns.Resolve("host.contoso.com");
    IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);   Socket s = new Socket(lep.Address.AddressFamily,
                                      SocketType.Stream,
                                         ProtocolType.Tcp);
       try{
          
                 while(true){
                 allDone.Reset();             byte[] buff = Encoding.ASCII.GetBytes("This is a test");
                 
                 Console.WriteLine("Sending Message Now..");
                 s.BeginSendTo(buff, 0, buff.Length, 0, lep, new AsyncCallback(Async_Send_Receive.SendTo_Callback), s);             allDone.WaitOne();
            }
       }
       catch (Exception e){
            Console.WriteLine(e.ToString());
       }
      

  2.   

    If you are using a connection-oriented protocol, you must first call the Connect, BeginConnect, Accept, or BeginAccept method, or BeginSendTo will throw a SocketException. BeginSendTo will ignore the remoteEP parameter and send data to the EndPoint established in the Connect, BeginConnect, Accept, or BeginAccept method.If you are using a connectionless protocol, you do not need to establish a default remote host with the Connect or BeginConnect method prior to calling SendTo. You only need to do this if you intend to call the BeginSend method. If you do call the Connect or BeginConnect method prior to calling SendTo, the remoteEP parameter will override the specified default remote host for that send operation only. You are also not required to call the Bind method. In this case, the underlying service provider will assign the most appropriate local network address and port number. If you need to identify the assigned local network address and port number, you can use the LocalEndPoint property after the EndSendTo method successfully completes.
    如果当前使用的是面向连接的协议,则必须首先调用 Connect、BeginConnect、Accept 或 BeginAccept 方法,否则 BeginSendTo 将会引发 SocketException。BeginSendTo 将会忽略 remoteEP 参数并将数据发送给在 Connect、BeginConnect、Accept 或 BeginAccept 方法中建立的 EndPoint。如果当前使用的是无连接协议,则在调用 SendTo 之前,不需要使用 Connect 或 BeginConnect 方法来建立默认远程主机。仅当打算调用 BeginSend 方法时,才需要这样做。如果在调用 SendTo 之前确实调用了 Connect 或 BeginConnect 方法,则 remoteEP 参数将只为该发送操作重写指定的默认远程主机。此外,您还不需要调用 Bind 方法。在这种情况下,基础服务提供程序将会分配最合适的本地网络地址和端口号。如果您希望基础服务提供程序选择可用端口,请使用端口号 0。如果需要标识分配的本地网络地址和端口号,可以在 EndSendTo 方法成功完成后使用 LocalEndPoint 属性。
      

  3.   

    http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.beginsendto.aspx
      

  4.   

    如果使用TCP,在发送数据前当然需要建立连接.
    如果使用UDP,可以直接发送,不需要建立链路
      

  5.   

    1楼的有些问题吧?
    使用 while(true){}这个死循环会不停地发送吗?
    2楼的基本正确,来自MSDN。如果使用面向连接,必须先CONNECT