Step 1:.
Save the following code file: week13_network.pyde. Rename it to whatever you'd like. Once you download it, you should be able to simply drag it into your sketch window to add it as a new tab to your sketch. Then, in your main tab, add the following line:
from week13_networking import *
Or if you have named your tab something else, specify that name instead.
Next, look in the tab. This code has two variables at the
top: ip_address
and port
. You'll need
to set these to the IP address and port of the server you're
trying to connect to. For this example, we'll be using:
ip_address = "174.138.45.118" port = "5000"
For testing locally, you can leave the address as 127.0.0.1
If you'd like, have a look at this code. It defines two
functions: getData(cList)
and sendData(c)
. getData()
retrieves a
JSON file from a webserver with the given IP
address, then it populates a list of dictionaries, and
returns that list. You would use it like this:
creatureList = getData()
sendData(c)
sends the data about one single
"creature" to this webserver. This webserver
has its own Python code which saves this data into a list and
distributes it to anyone who calls getData(cList)
.
In order to run this, you will also need to modify the main tab
to change myCreature["name"]
to something. It
doesn't have to be your name obviously, but it does have to be
unique among everyone else in the class. You should also modify
the color values on line 10.
Putting that altogether would look like this:
You will also have to modify the code in the networking tab to add/delete the properties that you're sending to the server and receiving from the server.
Now, if you run this code (and the webserver is turned on and running!) you should be able to move your creature around, while also seeing the moving creatures of anyone else currently connecting to this webserver.
Step 2:.
Get the server code: week13-web-server.py. This is a relatively short amount of code, but it is using a lot of things that we have not talked about yet. Mainly, this is using a Python web server library called Flask, which you can read about if you are curious.
Open the command line, cd
to the
directory where you saved the above file, and run this command:
$ python -m flask --app server run
Then you should be able to run your Processing sketch and have it communicate to the server.
To run a second instance, you'll need to copy your entire Processing sketch folder, rename it to something else (like "player2") and run that. Delete it when you close it so you don't get mixed up about where you're making changes.