8

我有一个使用 UDP 套接字发送数据的客户端-服务器应用程序,数据只需从客户端传输到服务器,并且服务器将始终具有相同的 IP。唯一的要求是我必须每秒发送大约 10 条消息

目前我正在通过以下方式进行操作:

public void SendData(byte[] packet)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
    udpChannel.Send(packet, packet.Length);
    udpChannel.Close();
}

我遇到的问题是,当我使用命令“udpChannel.Close()”时,服务器未在监听时需要 2-3 秒才能执行。(我在:如果我不调用 UdpClient.Close() 方法有什么缺点?

我的问题是,如果我总是将数据包发送到相同的 IP 地址和端口,是否有必要在每次发送请求后连接套接字并关闭它?

我打算使用的代码如下:

UdpClient udpChannel;

public void SendData(byte[] packet)
{
    udpChannel.Send(packet, packet.Length);
}

public void Initialize(IPAddress IP, int port)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
}

public void Exit()
{
    udpChannel.Close();
}

这样做,是否有必要在发送数据之前对“SendData”方法进行一些检查?上面的代码有问题吗?

谢谢!

4

3 回答 3

12

UDP 是无连接的,调用 udpChannel.Connect 仅指定一个默认主机端点以用于 Send 方法。您无需在发送之间关闭客户端,将其打开不会留下任何连接或侦听器在发送之间运行。

于 2013-11-06T18:36:23.743 回答
3

您不应在每次发送请求后连接/关闭。当您开始工作时 - 您连接到套接字。你可以发送数据。当您不想发送/接收数据时,您应该关闭 UdpClient,例如当您关闭表单时。

在您的情况下,您可以检查udpClient != null关闭/发送客户端时是否可以使用 try/catch,例如:

try
{
    udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception exc)
{
    // handle the error
}

连接时使用 try/catch,因为端口可能正忙或其他连接问题。看看UdpClient.SendAsync :)

于 2013-11-06T20:05:46.720 回答
0
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Net.Sockets;
using System;
using System.Net;

public class Server : MonoBehaviour
{
    //int[] ports;
    UdpClient udp; // Udp client

    private void Start()
    {
        udp = new UdpClient(1234);
        udp.BeginReceive(Receive, null);
    }

    void Send(string msg, IPEndPoint ipe)
    {
        UdpClient sC = new UdpClient(0);
        byte[] m = Encoding.Unicode.GetBytes(msg);
        sC.Send(m, msg.Length * sizeof(char), ipe);
        Debug.Log("Sending: " + msg);
        sC.Close();
    }

    void Receive(IAsyncResult ar)
    {
        IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
        byte[] data = udp.EndReceive(ar, ref ipe);
        string msg = Encoding.Unicode.GetString(data);
        Debug.Log("Receiving: " + msg);

        udp.BeginReceive(Receive, null);
    }
}

在 Send() 处,我使用新的 UDP 客户端并在每次之后关闭它。更好的是,你可以同时发送和接收。

于 2017-11-17T17:20:16.237 回答