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

时间:2019-01-25 08:43:57

标签: php signalr

我们正在开发一个汽车预订应用程序,使其可以与PHP服务器一起使用。该移动应用已在使用Signal R与.NET服务器进行实时通信。我们想要修改代码以连接到我们的PHP服务器。

我的问题是如何连接此信号R代码以与PHP服务器通信?信号R如何与PHP服务器一起使用?有什么解决办法吗?

我们的主要目标是使其与信号R一起使用,而不是切换到其他解决方案。不过,我还是很感谢您的建议。

这是需要与PHP服务器通信的Java代码

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 个答案:

没有答案