1

我的 WebSocket 结构如下。

public HttpResponseMessage Get(int id, string kod)
{
    if (HttpContext.Current.IsWebSocketRequest)
    {
        HttpContext.Current.AcceptWebSocketRequest(new SocketHandler(id, kod));      
        return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

class SocketHandler : WebSocketHandler
{
    DnaEntities db = new DnaEntities();

    private static WebSocketCollection Clients = new WebSocketCollection();
    private Yonetim_Kullanici Kullanici;

    public SocketHandler(int KullaniciId, string OturumKontrolKod)
    {
        var sorgu = db.Yonetim_Kullanici.Where(k => k.Id == KullaniciId && k.OturumKontrolKod == OturumKontrolKod && k.Durum == 1);
        if (sorgu.Count() == 1)
        {
            Kullanici = sorgu.FirstOrDefault();
        }
    }

    public override void OnOpen()
    {
        if (Kullanici != null)
        {
            Clients.Add(this);
        }
        base.OnOpen();
    }
    public override void OnClose()
    {
        Clients.Remove(this);
        base.OnClose();
    }

    public override void OnMessage(string data)
    {
        foreach (var item in Clients)
        {
            var data = item.Kullanici
            //item.Send();
        }
    }

如下,我可以发给大家。

Clients.Broadcast(message);

但是,当我想一一发送时:

foreach (var item in Clients)
{
    var UserModel = item.Kullanici;
}

错误信息:

“WebSocketHandler”不包含“Kullanici”的定义,并且找不到接受“WebSocketHandler”类型的第一个参数的扩展方法“Kullanici”。

item.Kullanici => 如图所示

4

1 回答 1

1

我认为您应该能够首先将其转换为继承的类,例如

var UserModel = ((SocketHandler)item).Kullanici

你还没有展示它,但我会假设其中的项目Clients是类型WebSocketHandler

于 2018-05-30T15:06:01.293 回答