从服务器向客户端发送数据包不够快(包含代码)

本文关键字:包含 代码 不够 数据包 服务器 客户端 | 更新日期: 2023-09-27 18:02:34

我正在用c#编写一个视频会议应用程序,我遇到了一些视频延迟问题,

客户端将从webcome获取图像,每秒10帧,并使用TCP(很快将转换为UDP)将它们(一个接一个)发送到服务器。我使用Socket。发送,socket阻塞。'

if (VideoSoc != null)
{
    try
    {
        VideoSoc.SendBufferSize = picChunk.Length;
        VideoSoc.Send(picChunk);
        sendimage++;
    }
    catch (SocketException expp)
    {
        if (expp.ErrorCode == 10054)
        {
            //ConnectSockets();
            //MessageBox.Show("Video has been disconnected.");
        }
    }
    catch (Exception exppp) { }
}

在服务器上有一个Room类和一个User类,每个连接到它们的User将有一个类型为byte[]的队列来存储该用户收到的图像。

List<byte> bl = new List<byte>(VideoPacket.Videobuffer);
bl.RemoveRange(iRx, VideoPacket.Videobuffer.Length - iRx);
byte[] nb = new byte[bl.Count];
bl.CopyTo(nb);
Rooms[VideoPacket.Index].UsersList[VideoPacket.Pos].VideoList.Enqueue(nb);

然后在While(true)循环中,在与主线程不同的线程上,服务器将遍历用户列表,获取存储在队列中的图像,并使用udp套接字将其发送给所有其他连接的客户端。

while (true)
{
    try
    {
        for (int x = 0; x < Rooms[roomindex].UsersList.Count; x++)
        {
            try
            {
                // this is my temp solution to eliminate the delay.. if more than 10 frames are stacked up in the ques.. clear them, which will effect the smoothness of the video on the client side
                if (Rooms[roomindex].UsersList[x].VideoList.Count >10)
                {
                    Rooms[roomindex].UsersList[x].VideoList.Clear();
                }
                countt = Rooms[roomindex].UsersList[x].VideoList.Count;
                if (Rooms[roomindex].UsersList[x].VideoList.Count > 0)
                {
                    byte[] videodata = Rooms[roomindex].UsersList[x].VideoList.Dequeue();
                    for (int i = 0; i < Rooms[roomindex].UsersList.Count; i++)
                    {
                        if (i != x && Rooms[roomindex].UsersList[i].Username != "u" && Rooms[roomindex].UsersList[i].Ready)
                        {
                            try
                            {
                                Rooms[roomindex].UsersList[i].udpvideosocket.SendTo(videodata, Rooms[roomindex].UsersList[i].ep);
                            }
                            catch(Exception ex) { }
                        }
                    }
                }
            }
            catch (Exception exo)
            {
                Rooms[roomindex].UsersList[x].VideoList.Clear();
            }
        }
    }
    catch (Exception VideoSendingException)
    {
         logerror(VideoSendingException);
    }

在这里我可以看到,当越来越多的新客户端连接时,每个用户的视频队列计数正在增加,这推动了upd套接字的结论。Send的速度不够快,无法将数据发送到20个连接的客户端。这就是我的问题。

我不是插座专家,我尽我最大的努力与谷歌搜索结果提供了一个更大的知识。我知道我的代码不是最好的,它没有优化,所以任何建议或指出正确的方向是受欢迎的。如有任何澄清,请随时要求。

<标题>谢谢。

由于UDP在NAT路由器后面临的困难,我回到使用TCP。

从服务器向客户端发送数据包不够快(包含代码)

From MSDN Socket。发送到:

If you are using a connectionless protocol in blocking mode, SendTo will block until the datagram is sent.

据我所知,这正是你正在做的。