douli2876 2019-01-25 08:43
浏览 101

将信号r客户端连接到PHP服务器以进行实时通信

We are working on a car booking app to make it work with a PHP server. the mobile app is already using Signal R for real-time communication with a .NET server. we want to modify the code to connect to our PHP server.

My question is how can I connect this signal R code to communicate to a PHP server? How signal R will Work with a PHP server? Any solution for that?

Our primary aim is to make it work with signal R instead of switching to other solutions. Still, I would appreciate your recommendations.

Here is Java code that needs to communicate with PHP server

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
using MyBuddyRide_APIs.Models;
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using SortApp.ChatService;
using MyBuddyRide_APIs.Helper_Snippets;
using System.Data.Entity;
using MyBuddyRide_APIs.Enums;
using System.Collections.Generic;

namespace MyBuddyRide_APIs.ChatService
{
    [HubName("brHub")]
    public class PrivateChatHub : Hub
    {
        private MBRDbContext db = new MBRDbContext();

        #region Internal Calls
        public override Task OnConnected()
        {
            return base.OnConnected();
        }

        public override Task OnReconnected()
        {
            return base.OnReconnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            string connectionId = this.Context.ConnectionId;
            User user = this.db.Users.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
            if (user != null)
            {
                user.ConnectionId = null;
                this.db.SaveChanges();
            }
            else
            {
                var driver = this.db.Driver.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
                if (driver != null)
                {
                    //get all the active vehicles, if any vehicle is not in progress, set vehicles status offiline
                    var veh = db.Vechicles.Where(s => s.Status == DriverStatus.InProgress || s.Status == DriverStatus.OnLine).FirstOrDefault();
                    if (veh != null)
                    {
                        if (veh.Status == DriverStatus.OnLine)
                        {
                            veh.Status = DriverStatus.OffLine;
                            RemoveDriver(driver.DriverId);
                        }
                    }

                    driver.ConnectionId = null;
                    this.db.SaveChanges();
                }
            }
            return base.OnDisconnected(stopCalled);
        }
        #endregion

        #region Rider Calls
        [HubMethodName("goOnlineUser")]
        public string GoOnlineUser(int userId)
        {
            try
            {
                if (userId > 0)
                {
                    string connectionId = this.Context.ConnectionId;
                    User user = this.db.Users.Where(s => s.UserId == userId).FirstOrDefault();
                    if (user != null)
                    {
                        user.ConnectionId = connectionId;
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();

                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        [HubMethodName("goOfflineRider")]
        public string GoOfflineRider(long riderId, string token)
        {
            try
            {
                if (riderId > 0)
                {
                    var user = this.db.Users.Where(s => s.UserId == riderId).FirstOrDefault();
                    if (user != null)
                    {
                        user.ConnectionId = null;
                        db.Entry(user).State = EntityState.Modified;

                        db.SaveChanges();

                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        [HubMethodName("getNearbyDriver")]
        public string GetNearbyDriver(long userId, string token)
        {
            try
            {
                if (userId > 0 && token != null)
                {
                    var user = db.Users.Where(s => s.UserId == userId && s.Token == token).FirstOrDefault();
                    if (user != null)
                    {
                        //get all the online drivers's location
                        var locations = db.Driver.Where(s => !s.InRide && s.ConnectionId != null && s.Vehicles.Where(e => e.Status == DriverStatus.OnLine).FirstOrDefault() != null).Select(s => new DriverLocationUpdate
                        {
                            bearing = s.Bearing,
                            driverId = s.DriverId,
                            lat = s.Latitude,
                            lon = s.Longitude
                        }).ToList();

                        return JsonConvert.SerializeObject(new HubResponse()
                        {
                            data = locations
                        });
                    }
                    else
                    {
                        return JsonConvert.SerializeObject((object)new HubResponse()
                        {
                            status = false,
                            message = "invalid User"
                        });
                    }
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }
        #endregion

        #region Driver Calls
        [HubMethodName("goOnlineDriver")]
        public string GoOnlineDriver(long driverId, int vehicleId = 0)
        {
            try
            {
                if (driverId > 0)
                {
                    string connectionId = this.Context.ConnectionId;
                    var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
                    if (user != null)
                    {
                        user.ConnectionId = connectionId;
                        db.Entry(user).State = EntityState.Modified;
                        if (vehicleId > 0)
                        {
                            //check if any vehicle was not in progress, then make it online
                            var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status != DriverStatus.InProgress).FirstOrDefault();
                            if (veh != null)
                            {
                                veh.Status = DriverStatus.OnLine;
                            }
                        }
                        db.SaveChanges();

                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        [HubMethodName("updateLocation")]
        public string UpdateDriverLocation(long driverId, int vehicleId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
        {
            try
            {
                if (driverId > 0 && vehicleId > 0)
                {
                    var user = this.db.Driver.Where(s => s.DriverId == driverId && s.Vehicles.Where(x=>x.VehicleId == vehicleId).FirstOrDefault()!=null).FirstOrDefault();
                    if (user != null)
                    {
                        user.Latitude = latitude;
                        user.Longitude = longitude;
                        user.Bearing = bearing;
                        db.Entry(user).State = EntityState.Modified;

                        db.SaveChanges();

                        //notify all the users who are not in ride

                        NewDriverLocation(new DriverLocationUpdate
                        {
                            driverId = user.DriverId,
                            bearing = bearing,
                            lat = latitude,
                            lon = longitude
                        });

                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        [HubMethodName("goOfflineDriver")]
        public string GoOfflineDriver(long driverId, int vehicleId = 0)
        {
            try
            {
                if (driverId > 0)
                {
                    var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
                    if (user != null)
                    {
                        user.ConnectionId = null;
                        db.Entry(user).State = EntityState.Modified;

                        if (vehicleId > 0)
                        {
                            //put the online vehicle offline
                            var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status == DriverStatus.OnLine).FirstOrDefault();
                            if (veh != null)
                            {
                                veh.Status = DriverStatus.OffLine;
                                RemoveDriver(driverId);
                            }
                        }

                        db.SaveChanges();

                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }
        #endregion

        #region Chat Calls
        [HubMethodName("getAllChats")]
        public string GetAllChats(int rideId)
        {
            try
            {
                var ride = db.Rides.Where(s => s.RideId == rideId).FirstOrDefault();

                if (ride == null)
                {
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "Unknows Ride!"
                    });
                }

                var resp = db.PrivateChats.AsNoTracking().Where(e => e.Ride.RideId == rideId).AsEnumerable().Select(s => new HubChatMessage
                {
                    message = s.Message,
                    rideId = rideId,
                    datetime = s.Time.ToString("MM/dd/yyyy HH:mm"),
                    sender = s.Sender
                }).ToList();
                HubResponse hubResponse = new HubResponse
                {
                    data = resp
                };
                return JsonConvert.SerializeObject(hubResponse);
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        [HubMethodName("sendMessage")]
        public string SendMessage(int rideId, string sender, string message, string datetime)
        {
            try
            {
                var ride = db.Rides.Include("User").Include("Driver").Where(s => s.RideId == rideId).FirstOrDefault();
                if (ride != null)
                {
                    if (ride.User == null || ride.Driver == null)
                    {
                        return JsonConvert.SerializeObject((object)new HubResponse()
                        {
                            status = false,
                            message = "Invalid Ride Session!"
                        });
                    }

                    //receiver
                    string connectionId = null;

                    if (sender == "rider")
                    {
                        connectionId = ride.Driver.ConnectionId;
                    }
                    else
                    {
                        connectionId = ride.User.ConnectionId;
                    }

                    var newMessage = new HubChatMessage
                    {
                        datetime = datetime,
                        message = message,
                        sender = sender,
                        rideId = rideId
                    };

                    var privateChatMessage = new PrivateChatMessage
                    {
                        Message = message,
                        Time = DateTime.ParseExact(datetime, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture),
                        Sender = sender,
                        Ride = ride
                    };
                    db.PrivateChats.Add(privateChatMessage);

                    db.SaveChanges();

                    if (connectionId != null)
                    {
                        //call client side method.s
                        NewMessage(connectionId, newMessage);
                    }
                    else
                    {
                        if (sender != "rider")
                        {
                            //send push
                            SendPushNotifications push = new SendPushNotifications();
                            push.NotifyPerson(ride.User.UserId, message, "New Message", newMessage);
                        }
                        else
                        {
                            //send push
                            SendPushNotifications push = new SendPushNotifications();
                            push.NotifyDriver(ride.Driver.DriverId, message, "New Message", newMessage);
                        }
                    }

                    return JsonConvert.SerializeObject((object)new HubResponse()
                    {
                        message = "message sent"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid message"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }
        #endregion

        #region Ride Session
        [HubMethodName("updateCaptainLocation")] //Captain's location who accepted the request will sync his location to rider
        public string UpdateCaptainLocation(long rideId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
        {
            try
            {
                if (rideId > 0)
                {
                    var userConnId = db.Rides.Where(s => s.RideId == rideId).Select(s => new
                    {
                        s.Driver.DriverId,
                        s.User.ConnectionId
                    }).FirstOrDefault();
                    if (userConnId != null)
                    {
                        if (userConnId.ConnectionId != null)
                        {
                            //notify rider
                            NewCaptianLocation(userConnId.ConnectionId, new DriverLocationUpdate
                            {
                                driverId = userConnId.DriverId,
                                bearing = bearing,
                                lat = latitude,
                                lon = longitude
                            });
                        }
                        return JsonConvert.SerializeObject(new HubResponse());
                    }
                    return JsonConvert.SerializeObject(new HubResponse()
                    {
                        status = false,
                        message = "unable to update status"
                    });
                }
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = "invalid userId"
                });
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return JsonConvert.SerializeObject((object)new HubResponse()
                {
                    status = false,
                    message = ("some error occured!: " + ex.Message),
                    data = (object)ex.InnerException
                });
            }
        }

        #endregion

        #region Client Side Invocations

        private void NewMessage(string connectionId, HubChatMessage newMessage)
        {
            Clients.Client(connectionId).newMessage(JsonConvert.SerializeObject(newMessage));
        }
        //notify all the online users
        private void NewDriverLocation(DriverLocationUpdate location)
        {
            var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
            if (onlineUsers.Count > 0)
            {
                Clients.Clients(onlineUsers).newDriverLocation(JsonConvert.SerializeObject(location));
            }
        }

        //notify the rider about his captian location. 
        private void NewCaptianLocation(string riderConnectionId, DriverLocationUpdate location)
        {
            Clients.Client(riderConnectionId).newCaptainLocation(JsonConvert.SerializeObject(location));
        }

        //notify users to remove driver from map as he's offline.
        private void RemoveDriver(long driverId)
        {
            var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
            if (onlineUsers.Count > 0)
            {
                Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
                {
                    driverId = driverId
                }
                ));
            }
        }

        #endregion

        #region Controller Helpers
        /// <summary>
        /// Helper function for Ride controller to remove the driver who have accepted the ride request
        /// This pirtucular driver should not send his location to all users except the one who have requested him.
        /// </summary>
        /// <param name="driverId"></param>
        /// <param name="onlineUsers"></param>
        public static void RemoveDriverWhenInRide(long driverId,List<string> onlineUsers)
        {
            if (onlineUsers.Count > 0)
            {
                var hub = GlobalHost.ConnectionManager.GetHubContext<PrivateChatHub>();
                hub.Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
                {
                    driverId = driverId
                }
                ));
            }
        }
        #endregion
    }
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
    • ¥15 gradio的web端页面格式不对的问题
    • ¥15 求大家看看Nonce如何配置
    • ¥15 Matlab怎么求解含参的二重积分?
    • ¥15 苹果手机突然连不上wifi了?
    • ¥15 cgictest.cgi文件无法访问
    • ¥20 删除和修改功能无法调用
    • ¥15 kafka topic 所有分副本数修改
    • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
    • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?