User File #73828291091638552

Upload All User Files

#73828291091638552 - DK64 net-receive.lua

dk64-net-receive.lua
Game: Donkey Kong 64 ( N64, see all files )
189 downloads
Uploaded 8/29/2021 8:40 PM by Zinfidel (see all 12)
Sync script modified to work on very old versions of BizHawk, with code specific to syncing DK64.
package.path = package.path .. ';luasocket/lua/?.lua;luasocket/lua/socket/?.lua'
package.cpath = package.cpath .. ';luasocket/?.dll;luasocket/mime/?.dll;luasocket/socket/?.dll'
local socket = require 'socket'

local socClient
local server

local onExitEvent = event.onexit(
	function()
		socClient:close()
		server:close()
		console.log("Client closed.")
	end
	, "Exit Event" );

local function endsWith(str, ending)
	return ending == "" or str:sub(-#ending) == ending
end

local function strChop(str, ending)
	return str:sub(1, -(#ending + 1))
end

-- Pause the client and establish a socket listener.
client.pause()
server = assert(socket.bind("127.0.0.1", 45678), "Socket server failed to bind to ip/port. Script aborted.")
console.write("Waiting on connection...")
emu.yield()

server:settimeout(5)
server:setoption('keepalive', true)

-- Wait for the other instance to connect.
while true do
	local err = nil
	socClient, err = server:accept()

	if not err then
		console.log(" Connected!")
		emu.yield()
		break
	else
		console.write('.')
	end
	emu.yield()
end

socClient:settimeout(10)

console.write("Awaiting a message ...")
while true do
	emu.yield()
	local line, err = socClient:receive()
	if not err then
		if line == "quit" then
			console.log("\nReceived exit message. Exiting now.")
			break;
		elseif endsWith(line, ".State") then
			local frameNum = tonumber(strChop(line, ".State"))
			console.write("\nReceived request for a savestate at frame " .. tostring(frameNum) .. ". Seeking...")
			emu.yield()

			client.unpause()
			while emu.framecount() ~= frameNum do
				emu.frameadvance()
			end
			client.pause()

			savestate.save("states/" .. line)
			console.log("\nCreated " .. line .. ". Sending to the client.")
			emu.yield()
			socClient:send(line .. "\n")
			console.write("\nAwaiting a message ...")
		else
			console.log("\nUnknown command " .. line .. " received.")
		end
	elseif err == "timeout" then
		console.write('.')
	elseif err == "closed" then
		console.log("\nConnection with client closed. Exiting now.")
		break;
	else
		console.log("\nNo message received. Error: " .. err)
	end
	emu.yield()
end