Skip to content

Get connection id from composable #5

Open
@rahmedd

Description

@rahmedd

Hi, thank you for your work on this library!

I'm making a multiplayer game, with multiple game lobbies. I want to make an HTTP request to an ASP.NET API to ensure that the game lobby name requested is unique, and then use hubcontext within that same ASP.NET controller to add that player to the SignalR group. Because I'm using the SignalR hubcontext in an ASP.NET controller, it has no access to the SignalR event state/context and doesn't know what the connectionId is, so I need to pass the connectionId as part of my HTTP request.

I want to be able to send the SignalR connectionId from the Vue client to the ASP.NET endpoint.
How can I do that? Is there a way to access the connection instance after it's been connected? Somewhere after vue-signlar init() calls connection.start()?

Frontend (initialization) main.ts

...
const connection = new HubConnectionBuilder()
	.withUrl('/api/hub')
	.withAutomaticReconnect()
	.build()

const app = createApp(App)

app.use(VueSignalR, {
	connection,
	autoOffInsideComponentScope: true,
	failFn: () => {
		console.log('signalr conn failed.')
	},
})
...

Frontend usage store.ts

export const useRoom = defineStore('room', () => {
	const signalr = useSignalR()
	const roomState = ref<Room | null>(null)

	signalr.on('Send', message => {
		console.log(`Send: ${JSON.stringify(message)}`)
	})

	signalr.on('JSON-room', message => {
		const res = JSON.parse(message)
		console.log(res)
		roomState.value = res
	})

	async function createGame(roomCode: string, nickname: string) {
		try {
			const res = await axios.post(`${import.meta.env.VITE_API_URL}/Room/CreateGame`, {
				connectionId: 'NOT_IMPLEMENTED',
				groupName: roomCode,
				username: nickname,
			})

			if (!res.data.success) {
				// handle game already exists error
			}
		}
		catch (ex) {
			console.log(ex)
		}
	}
})

Backend:

...
[HttpPost("CreateGame")]
public async Task<Results<Ok<BaseResponseEmpty>, ValidationProblem>> CreateGame(
	string connectionId,
	string groupName,
	string username
)
{
	var room = await _roomService.GetRoom(groupName);
	if (room != null)
	{
		return TypedResults.Ok(new BaseResponseEmpty(false, "Room already exists"));
	}

	await _roomService.CreateRoom(connectionId, groupName, username);
	await _hubContext.Groups.AddToGroupAsync(connectionId, groupName);

	var gameStateJson = await _roomService.GetRoomAsJson(groupName);
	await _hubContext.Clients.Group(groupName).SendAsync("JSON-room", gameStateJson); // push updated game state to all players
	
	return TypedResults.Ok(new BaseResponseEmpty(true, "Game created"));
}
...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions