Factorio headless server windows

Multiplayer

In addition to being a single-player game, Factorio also supports multiplayer, allowing many players to cooperate and assist each other, or work against each other in pvp. This page documents how to set up a multiplayer game, how to join one, and the Multiplayer Admin features for managing other users and the server. By default, multiplayer games run the CO-OP freeplay scenario where all players work together to launch a rocket with a satellite into space. Other scenarios, including PvP maps, are available for download from the Maps and Scenarios forum.

Contents

Setting Up a Multiplayer Game

Multiplayer games can be joined, hosted while playing, or hosted by a dedicated server. Multiplayer games can be advertised to other players on the same LAN or worldwide.

Use the Multiplayer button in the Play menu to start playing a multiplayer game, choose New or Load or Scenarios to host and play, or Browse or Play on LAN to connect to an already-running game. The host can also choose not to advertise the game at all, in which case you’ll need the server’s (public or otherwise reachable) IP address; you can then Connect directly to that to join the game.

Dedicated/Headless server

In the headless mode:

There are several JSON configuration files that factorio can make use of to change the server and map settings:

Example files for each of these parameters are included in the data subdirectory.

Starting the factorio server requires you to specify the location of the server-settings.json file. By default this is in the factorio data folder. For example to start factorio using the most recent saved map, you would run:

See Command_line_parameters for more command line parameters.

Setting up a Linux Factorio server

Note: Factorio now requires glibc version 2.18, but CentOS/RHEL 7 only ship with version 2.17 so this guide will no longer work without manually compiling glibc 2.18.

This step-by-step guide has been verified on fresh CentOS 7 and RHEL 7 installs but should be applicable with little to no changes on most distributions.

The guide assumes you will install the headless server under /opt/factorio, adjust paths according to your own setup. We will also suggest that you run the Factorio server as a separate user to harden security of your setup.

Note that there are two distinct packages for Linux that can be used to run a headless server. First is the usual Linux download, that contains the full game. The other is the special headless package. The headless package does not contain any files irrelevant for a pure server, such as graphics and sounds. It is also not linked against libraries that may not be present on a server machine, such as Xlib, libGL or libasound. This option should be selected if running in a 3rd party hosted server.

This guide does not handle firewall/port forwarding since this can be done in various ways on Linux (make sure to read up how this is done as a Linux admin on your particular distribution)

Basic installation

Additional configuration

You can use a Linux factorio-init script to start/stop your headless server in a much better way. The script will ensure you only ever use the most recent save when your server starts (even if that was an auto-save) while also letting you set a number of other settings like Autosave frequency and Latency settings. This script can also simplify updating the server when combined with a Linux factorio-updater script. Alternatively, Docker can be used to run the server: factorio docker container.

Additionally, if you plan to enable mods on your server a mod updater script can greatly simplify this process. Here are several existing options, or you can write your own!

How to list a server-hosted game on the matching server

In order to publish the game to the matching server, Factorio needs to be given some more information than just the save file location. These information are provided in a server settings file.

To create a server settings file, look at the example file located in data/server-settings.example.json in the Factorio Application directory. The recommended way is to make a copy of this example file and edit the copy.

The following values can be changed:

(There are additional values in v0.14 of factorio.)

Technical Implementation Details

Notes about some technical details surrounding multiplayer have been published by the development team in several Friday Facts blog posts:

Miscellaneous Tips

r, g and b are for red, green and blue respectively (possible values are between 0 and 1, use this site to convert colors to rgb numbers).

This file will be created if you promote a player through the console.

Joining a Multiplayer game

As of version 0.13, players no longer necessarily have to port-forward to play with others. Players may join each other through Steam, or by just the port-forwarded host.

Players wishing to join a game may do so in multiple ways:

Joining by IP

If the server has been set up correctly to accept public connections, you should be able to join the game.

Читайте также:  Microsoft health для windows

Joining via server list

Joining through Steam

Steam provides a «game invite» system, simply use that to join. You can find more info about how to use steam in it’s documentation. This is the most recommended way for the average player to use multiplayer with their friends, as it allows Steam to handle everything.

Joining a local LAN game

Finding Other Players

Connecting to a Server Behind NAT

Factorio requires that the server (in client-server mode) have a publicly accessible IP address or that all players are on the same LAN. If you are behind NAT, you must set up port forwarding (see above for port number) or use virtual LAN software such as Hamachi or Evolve.

Multiplayer games will be launched in client-server mode (also multiplayer forwarding mode). In this mode, all clients send their network traffic to the server and the server forwards the traffic to the other clients. The advantage of this is that it allows games where some players are inside a LAN and others are outside. The disadvantage may be slightly more lag as packets must travel an extra hop (through the server).

In PvP mode, players can be on different forces. Each force can have one (free-for-all) or more players (teams). Each force has its own independent research progression. Additionally, each force’s Military units and structures will attack other players as enemies, unless a cease fire is set. Note that, depending on the scenario, cease fires may be unidirectional — setting a cease fire with an opposing force does not guarantee a cease fire from them in return.

To start a PvP game, you can select the ‘PvP’ scenario from the ‘Play’ menu, or download a custom scenario which also supports PvP.

After downloading a PvP scenario, you need to move it to your application directory, and create the multiplayer game using the scenario.

Forces

Forces can be manually created via the console. This allows any map/scenario to be used for PvP. This may not be as convenient as a pre-made PvP scenario, as there will be no way for players to turn on/off cease fires other than through the console.

Each created force has its own research progression and different forces may attack each other.

The console commands for setting up and controlling forces are below:

The ability of players and entities belonging to one force to interact with structures belonging to another, non-friendly force is limited. However, some types of interactions are still possible:

Manual pickup from belts Players can pick up items traveling along a transport belt that belongs to an opposing force. Note however that this can’t be automated: Inserters will not take items from an opposing force’s belts. Belt network connection Belts will connect to each other regardless of force membership, so it’s possible to extend an opposing force’s belt line, and items will flow to them. It is also possible to side-load into, and place items onto (with inserters) an opposing force’s belt line. Fluid network connection Pipes (and storage tanks, and pumps, &c) will connect to each other regardless of force membership. For example, it’s possible to pump fluids out of or into a storage tank belonging to an opposing force. Power leeching Players can draw power from an opposing force’s electric network, by building structures inside the coverage area of a power pole belonging to an opposing force. Power poles that you build next to a power pole belonging to an opposing force will automatically connect to it, but will be impossible to connect or disconnect manually.

History

Narrative history

Because of the potentially immense amount of activity on a map, the game engine utilizes a lock step architecture. All instances of the game run full simulations of the entire world and only player actions are transferred across the network.

Multiplayer games were introduced to Factorio with version 0.11.0. The only connection method available was peer-to-peer mode which meant every player had to be able to directly communicate with every other player. In version 0.12.4, a client-server mode of communication was introduced in which the server (either a dedicated one or the player who hosted the game) relays messages to all peers. This means that direct connection between all players is no longer necessary. As of version 0.13, P2P connecting is completely removed.

As of version 0.12.0, the game features «latency hiding» mechanics where the game simulates some of the player’s actions locally to make some common interactions (such as moving the player’s character) more fluid. Not every action is a part of latency hiding – most notably, car or train driving and shooting are not a part of it.

Version history

Maintainer note: The following history may not be fully up to date, or comprehensive. Factorio’s multiplayer has undergone a great deal of small changes since its inception, however this history will provide a rough overview.

Источник

othyn / factorio_headless_guide.md

[LINUX] Factorio Headless Server Guide

So, with credit to the Factorio wiki and cbednarski’s helpful gist, I managed to eventually setup a Factorio headless server. Although, I thought the process could be nailed down/simplified to be a bit more ‘tutorialised’ and also to document how I got it all working for my future records.

Just a note to newcomers: If there are any issues with the installation steps, people in the comments are doing a good job at mentioning steps required by newer installations. I don’t really play anymore and haven’t setup or managed a Factorio server in years, so I’ll advise if something isn’t working to check the comments and forks. Much love

I’m very much into Docker these days, in which there is a brilliant container setup and ready for this if you wish to use that instead.

Читайте также:  Asphalt 9 windows 10 не запускается

Step 0 :: Patches & Security!

If your server is running from behind your edge router/firewall, then enabling the firewall isn’t a necessary step. So skip to the next step if you don’t want to enable it.

As this is an internet facing server, you may want to install and configure something like fail2ban to help with repeated non-authorised login attempts, but that is up to you.

I’m going to be working out of my home directory, just for simplicity. Let’s grab the headless server from Factorio’s download site via wget onto the server.

Unfortunately, the url for the download isn’t static, so you’ll have to change the version in the url to what version you require (stable or experimental). Easiest way to find out the url is to go to the Factorio server download page and find the url from the link provided under the version number.

Wait for the file to download before proceeding.

Step 2 :: Directories

Just for the sake of keeping things tidy, I’d also delete the downloaded archive rm

Step 3 :: Environment

As you don’t want Factorio running as root, let’s setup a user that it can run under. The user won’t need a lot of functionality, as it’s only going to be running Factorio and won’t need to be logged into, so let’s provide some flags to create a really basic user:

Step 4 :: Factorio Configuration

Factorio headless, as of 0.14.12, requires a JSON formatted config file. They provide an example one to get you started, in which can be copied and then edited to suit your requirements.

The configuration is fairly straight forward and mirrors that of the GUI when setting up a server via the standard edition of Factorio. Here is the configuration reference. Configure it as you wish, save, exit and proceed onto the next step.

Save the file and exit. Time to start the service and see if our setup has worked!

Step Finished :: Play!

That’s it! You should now have a working Factorio server. Head over to your client and under «Multiplayer» > «Connect to a server», provide your address that you set it up against (and port if you changed it from the default) and play spend hours labouring over tiny details to maximize efficiency!

Источник

Мегапакет: как разработчикам Factorio удалось решить проблему с мультиплеером на 200 игроков

В мае этого года я участвовал в качестве игрока в MMO-мероприятии KatherineOfSky. Я заметил, что когда количество игроков достигает определённого числа, через каждые несколько минут часть из них «отваливается». К счастью для вас (но не для меня), я был одним из тех игроков, которые отключались каждый раз, даже при наличии хорошего подключения. Я воспринял это как личный вызов и начал искать причины проблемы. Спустя три недели отладки, тестирования и исправлений ошибка наконец устранена, но это путешествие было не таким уж простым.

Проблемы многопользовательских игр очень трудно отследить. Обычно они возникают в очень конкретных условиях параметров сетей и при очень специфичных состояниях игры (в данном случае — наличие более 200 игроков). И даже когда удаётся воспроизвести проблему, её невозможно должным образом отлаживать, потому что вставка контрольных точек останавливает игру, путает таймеры и обычно приводит к завершению соединения из-за превышения срока ожидания. Но благодаря упорности и замечательному инструменту под названием clumsy мне удалось выяснить, что же происходит.

Если вкратце: из-за ошибки и неполной реализации симуляции состояния задержки клиент иногда оказывался в ситуации, когда ему приходится за один такт отправлять сетевой пакет, состоящий из вводимых игроком действий выбора примерно 400 игровых сущностей (мы называем его «мегапакетом»). После этого сервер не только должен правильно получить все эти действия ввода, но и отправить их всем остальным клиентам. Если у тебя 200 клиентов, это быстро становится проблемой. Канал к серверу быстро забивается, что приводит к утере пакетов и каскаду повторно запрошенных пакетов. Откладывание действий ввода затем приводит к тому, что ещё больше клиентов начинает отправлять мегапакеты, и их лавина становится ещё сильнее. Удачливым клиентам удаётся восстановиться, все остальные «отваливаются».

Проблема была достаточно фундаментальной, и у меня ушло 2 недели на её устранение. Она довольно техническая, поэтому ниже я объясню сочные технические подробности. Но для начала вам нужно знать, что с версии 0.17.54, выпущенной 4 июня, в условиях временных проблем с подключением мультиплеер стал более стабильным, а сокрытие задержек — гораздо менее глючным (меньше торможений и телепортирования). Кроме того, я изменил способ сокрытия задержек в бою и надеюсь, что благодаря этому они будут немного более плавными.

Многопользовательский мегапакет — технические подробности

Если объяснять упрощённо, то мультиплеер в игре работает следующим образом: все клиенты симулируют состояние игры, получая и отправляя только ввод игрока (называемый «действиями ввода», Input Actions). Основная задача сервера — передача Input Actions и контроль того, что все клиенты выполняют одинаковые действия в одном такте. Подробнее об этом можно прочитать в посте FFF-149.

В Factorio есть игровое состояние Game State — это полное состояние карты, игрока, сущностей и всего остального. Оно детерминированно симулируется во всех клиентах на основании действий, полученных от сервера. Игровое состояние священно, и если оно когда-нибудь начинает отличаться от сервера или любого другого клиента, то возникает рассинхронизация.

Кроме Game State у нас есть состояние задержек Latency State. Оно содержит небольшое подмножество основного состояния. Latency State не священно и просто представляет картину того, как будет выглядеть состояние игры в будущем на основании введённых игроком Input Actions.

Для этого мы храним копию создаваемых Input Actions в очереди задержек.

То есть в конце процесса на стороне клиента картина выглядит примерно так:

Читайте также:  Windows xp поврежден системный файл

Слишком сложно? Не расслабляйтесь, это ещё не всё. Чтобы компенсировать ненадёжность Интернет-соединений, мы создали два механизма:

Теперь нужно объяснить вам, как работает выбор сущностей. Один из передаваемых типов Input Action — это изменение состояния выбора сущности. Оно сообщает всем, на какую сущность игрок навёл курсор мыши. Как можно понять, это одно из самых частых действий ввода, отправляемых клиентами, поэтому для экономии пропускной способности канала мы оптимизировали его так, чтобы оно занимало как можно меньше места. Это реализовано так: при выборе каждой сущности вместо сохранения абсолютных, высокоточных координат карты игра сохраняет низкоточное относительное смещение от предыдущего выбора. Это хорошо работает, потому что выделение мышью обычно происходит очень близко к предыдущему выделению. Из-за этого возникают два важных требования: Input Actions никогда нельзя пропускать и необходимо выполнять их в верном порядке. Эти требования удовлетворяются для Game State. Но поскольку задача Latency state в том, чтобы «выглядеть достаточно хорошо» для игрока, в состоянии задержек они не удовлетворяются. Latency State не учитывает многие пограничные случаи, связанные с пропуском тактов и изменением задержек передачи туда-обратно.

Вы уже можете догадаться, к чему всё идёт. Наконец мы начинаем видеть причины проблемы мегапакета. Корень проблемы заключается в том, что в принятии решения о том, нужно ли передавать действие изменения выбора, логика выбора сущностей полагается на Latency State, а это состояние не всегда содержит верную информацию. Поэтому мегапакет генерируется примерно так:

Мы решили эту проблему, исправив все пограничные случаи обновления и поддержки очереди задержек. Хоть это и заняло довольно много времени, в конечном итоге стоило реализовать всё правильно, а не полагаться на быстрые хаки.

Источник

Factorio Forums

Post by KFA » Tue Jul 30, 2019 11:01 pm

Story
So me, my little brother and my big brother had this vision of a Factorio server that would be constantly running even if no one was connected. So I sacrificed an old laptop to run Headless Factorio server and bought a mobile internet thingy (because they are cheap) and we started our journey. The thing with the mobile internet tho was that it sometimes changed IP address so I had to post status updates (that is, the new IP) to our whatsapp group. Getting tired of doing it manually I decided to write a program that would upload the new IP address automatically to a website that would have a static IP. All was fine until we decided to install some mods which resulted into Factorio server to crash occasionally which again meant that I had to manually restart the server everytime it did.
. And then the map got bigger which meant that the caching-up phase got intolerable (as map download took longer). And server-settings.json didn’t have any options to pause the server when a peer was connecting. So the program I initially wrote for a quick dirty fix got bigger and I got carried away.

So now that it works somewhat I decided I would share this program for all those who want it for similar reasons. Source code included.

Features
— Able to read console output and send input as well
— Restarts server if it crashes
— Able to pause the server when a peer is connecting, greatly reducing catching up phase
— Can write commands in-game to control the server
— Able to bind to public IP address to work as a server program that even has a GUI and can potentially be controlled from a website
— Able to to periodically connect to a selected web page so that e.g IP information can be uploaded
— Able to take real-time screenshots to send thru web page if requested (of the server interface, to see if the computer messed up, it can’t take in-game screenshots)

Static Website:

Web interface:

In-game:

Источник

Factorio headless server windows

Hi, so I want to know how to get multiple instances of factorio headless to run so I can get multiple servers up at the same time.

I read https://www.reddit.com/r/factorio/comments/6ijhqv/how_to_have_multiple_headless_servers_on_one_pc/ and the top comment of having different port and write directory makes sense. However, I do not know how to change the config settings correctly to have a different write directory. (I know how to set up server with different port)

in the config file it says

what would I change change after the equal sign to? =c:\something\something\something or is there something more complicated?

Also the question of where the default write directory is if it’s causing this issues. where is «write-data=__PATH__executable__\..\..» writing to?

Thanks. I am really bad with coding.

Why do people do this. I mean you don’t really come across 2+ year old threads unless you are specifically looking for them. Trying to help someone solve a problem they had 2 years ago when that person has not visited the forum since is kinda useless. Chances are they solved it themselves or no longer care about it at all.

Why do people do this. I mean you don’t really come across 2+ year old threads unless you are specifically looking for them. Trying to help someone solve a problem they had 2 years ago when that person has not visited the forum since is kinda useless. Chances are they solved it themselves or no longer care about it at all.

I answered this thread for people who have the same question as him/her.

I answered this thread for people who have the same question as him/her.

I have tested this before i answered this thread. You might look at this example to see if you are doing somethig wrong. The save is in the same directory as the bat file

Источник

Поделиться с друзьями
Советы экспертов и специалистов
Adblock
detector