C# - 将套接字协议从tcp更改为udp

时间:2015-12-09 00:34:01

标签: c# sockets serialization tcp udp

我制作了一个程序,它使用tcp Socket从服务器向多个客户端发送序列化数据。这个协议使我的用户操作过于复杂(在任何事情发生之前首先连接到服务器)我想使用udp套接字但是我找不到任何东西可以轻松学习如何这样做(并键入xmlSerializer而不是byte [])。 这是我创建TCPListener的代码:

public void CreateListener()
    {
        TcpListener tcpListener = null;
        try
        {
            tcpListener = new TcpListener(LocalIpAddress(), 8000);
            tcpListener.Start();
        }
        catch (Exception)
        {
            Console.WriteLine(@"Can't create Listener");
        }
        while (!_shouldStop)
        {
            Thread.Sleep(100);

            if (tcpListener != null)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                _clients.Add(client);
            }
            Console.WriteLine(@"clients : " + _clients.Count);
        }
        tcpListener?.Stop();
    }

以下是我发送和接收数据的方法:

public void SendDatas()
    {
        XmlSerializer xml = new XmlSerializer(typeof (DataSet));
        foreach (NetworkStream ns in from TcpClient client in _clients 
                   where client.Connected select client.GetStream())
        {
            xml.Serialize(ns, Controler.Database.DataSet);
            ns.Close();
        }
    }

    public void ReceiveDatas()
    {
        XmlSerializer xml = new XmlSerializer(typeof (DataSet));
        foreach (TcpClient client in _clients)
        {
            if (client.Connected)
            {
                NetworkStream ns = client.GetStream();
                var ds = (DataSet) xml.Deserialize(ns);
                /* treatment*/
                ns.Flush();
                ns.Close();
            }
            else
            {
                Console.WriteLine("Client non connecté !!");
            }
        }
    }

谢谢Menaren

0 个答案:

没有答案