CSE 219 Computer Science III

CSE 381
Advanced Game Programming
Sockets
Programming with TCP
• Transmission Control Protocol
• Has layers of error checking
• Guaranteed Packet Delivery
– All or error
– Makes it easier to deal with
– No worries for packet loss, packet splitting, packet
corruption
• Just keep an eye out for socket exceptions
Programming with UDP
• User Datagram Protocol
• No guaranteed delivery. You don't know:
– when your packet will get to its destination
– If it even made it there
– If your data was split into multiple piecees
• What's good about it?
– lightweight
ACKs
• TCP waits for ACKs from receiver
• What's an ACK?
– Acknowledgement
• TCP Application can wait for ACKs before sending
more. Why?
– prevent wasting bandwidth
• Alternative: nonblocking socket
Nonblocking Socket
• TCP Socket setting
• Doesn't wait for ACK after each send
• Allows you to stuff data in pipe as fast as you want
• Operates asynchronously
• As opposed to a blocking socket
– easier to program, less useful for game programming
Internet Addresses
• All computes with TCP/IP have unique IP Address
– some through their own network which provides
access point (LAN)
– i.e. unique to sub-net
• IPv4 32 bits
• IPv6 128 bits
– big enough so every living human may have their
own 5 x 1028 addresses
IPv4 Address Representations
• It's just a 32-bit number
• Decimal:
– 3486000987
– Not easy for humans to remember
• Hex:
– 0xCFC8275B
– not much better
• Dotted Decimal Format:
– 207.200.39.91
– now just remember 4 numbers
Sockets Libraries
• Handle low-level network communications. Ex:
– Berkeley Sockets
– WinSock
Sockets API
• Provide:
– Initialization and shutdown
– Utility functions
– Domain Name Service (DNS) functions
– Creating Sockets and Setting Socket Options
– Connecting client sockets to a server
– Server functions
– Reading and writing from sockets
Sockets Init & Shutdown
• Must startup library before using any other functions
int WSAStartup(WORD wVersionRequested,
LPWSADATA lpWSAData)
Ex:
WORD wVersionRequested = MAKEWORD(0, 2);
WSADATA wsaData;
int err = WSAStartup(wVersionRequested, &wsaData);
• When you're done, deregister the application:
int WSACleanup(void)
Utility Functions
• Help with conversions
• Ex:
unsigned long inet_addr(const char* cp)
• converts string IP (i.e. “127.0.0.1”) to num
htonl, ntohl, htons, ntohs
• used to convert endian-ness of numbers between
host machine order and network order
• Ex:
– Intel is little-endian
– Internet standard is big-endian
DNS Functions
• Help with locating hosts
• Ex:
struct hostent* FAR gethostbyname(
const char* name)
• gets host info, like IP address, by host name
struct hostent* FAR gethostbyaddr(
const char* addr, int len, int type)
• gets host info, like host name, by IP address
DNS Example
• Let's print the IP Address of microsoft
const char *host = "ftp.microsoft.com";
struct hostent *pHostEnt = gethostbyname(host);
if (pHostEnt == NULL)
fprintf(stderr, "No such host");
else
{
struct sockaddr_in addr;
memcpy(&addr.sin_addr,
pHostEnt->h_addr, pHostEnt->h_length);
printf("Address of %s is 0x%08x\n",
host, ntohl(addr.sin_addr.s_addr));
}
Address of ftp.microsoft.com is 0xcf2e858c
Creating Sockets
• To create a socket:
SOCKET socket(int address_family,
int socket_type, int protocol)
• Some families:
– PF_INET (Ipv4), PF_INET6, PF_DECnet,
PF_APPLE-TALK, PF_ATM
• Socket types:
– SOCK_STREAM, SOCK_DGRAM, SOCK_RAW
• Protocols
– IPPROTO_TCP, IPPROTO_UDP
Changing Socket Settings
• To change a socket:
int setsockopt(SOCKET socket, int level,
int optionName, const char* optionValue,
int optLen)
• Like what settings? Ex:
– disabling internal buffering (trade bandwidth for
speed)
• To specify socket as blocking/nonblocking:
int ioctlsocket(SOCKET s, long command,
u_long* argumentPointer)
Ex: Making a nonblocking Socket
• May only be called on a “live” socket
– a client connected to a server
– a server listening for clients
// 1 = unblocking, 0 = blocking
unsigned long val = 1;
ioctlsocket(m_sock, FIONBIO, &val);
But what are we going to connect to?
• A server waiting on a port for connections
• On server side specify where to listen:
int bind(SOCKET s,
const struct sockaddr* name, int namelen)
Then listen:
int listen(Socket s, int backlog)
And when a client requests a connection, accept it:
SOCKET accept(SOCKET listenSock,
const struct sockaddr* name, int namelen)
What if a client knocks on the door?
• When a client requests a connection, accept it:
SOCKET accept(SOCKET listenSock,
const struct sockaddr* name, int namelen)
Later, we can make sure the client is still there:
int select(int nfds, fd_set* readfds,
fd_set* writefds, fd_set* exceptfds,
const struct timeval* timeout))
So how does the client request a connection?
• Connect to listening server via connect:
int connect(SOCKET s,
const struct sockaddr* name, int namelen)
Socket Reading & Writing
• To send and receive bytes:
int send( SOCKET s, const char* buffer,
int length, int flags)
int recv( SOCKET s, char* buffer,
int length, int flags)
The send side is pushing bytes into the pipe
The recv side is pulling them out
So what do we do with sockets?
• Common multithreaded approach:
– Server Side:
• dedicate a thread to listen for each client
– Client Side:
• dedicate a thread to listen for server
• wire sockets into event system
Client Sockets & Events
• Translate network data into events
– recv packets
– interpret packets
– fire local events to update game state
• Translate events into network packets
– requires common event system contexts
• Implement translation through streaming system
– i.e. employ STL's istrstream & ostrstream
The Event System
• Requires contexts, meaning abstractions of different
types of events
• Event System obligations:
– for sending:
• translate events into contexts to send
• employ stream/sockets system to build and send
packets
– for receiving (after packet translated into context)
• wire contexts into actions (methods)
What’s an MMO?
MMO: Massively Multiplayer Online
MMOG: Massively Multiplayer Online Game
MMOPW: Massively Multiplayer Online
Persistent World
MMORTS: Massively Multiplayer Real Time
Strategy Game
MMORPG: Massively Multiplayer Role-Playing
Game
Everquest, Tactica online, Final Fantasy XI, etc.
Descendants of MUDs (Multi-User Dungeons)
1979, Roy Trubshaw and Richard Bartle
Types of MMOs
MMORPG
immersive worlds
replace your own life with that of your own avatar
typically each player controls a single unit
MMORTS
strategy & quick thinking more important
typically each player controls dozens of units
units may be visible, though far away
thousands of units may be visible at a time
more data transferring required than MMORPGs
have not yet caught on
Source: http://www.mmogchart.com/
Source: http://www.mmogchart.com/
Source: http://www.mmogchart.com/
MMORPG Demographics
Typical MMORPG player:
Male
13 – 34 years old
Median late 20s/early 30s
½ are heavy users, playing more than 18 hours/week
tend to play one game at a time
many still stay after maxing out game – why?
Most important feature to players?
character customization
Problems severe enough to make players consider leaving
game?
not enough new content, bugs, latency, cheating
MMO Costs
Everquest uses thousands of clustered server boxes
working together in a redundant network
a server box may contain multiple CPUs
each server can handle 200-300 players
additional redundancies necessary as well
Continually tweak balance to avoid “dead servers”
Other costs of course:
networking hardware
trained personnel
air conditioning
MMOs are a very expensive market to enter
As games get more popular, they get much more
expensive to maintain
small companies commonly sell growing games to larger
companies
Updating Data Revisited
Unique data challenges:
thousands of players share the same contiguous virtual
space
huge, expansive world
in many cases, user created
each player needs to receive information about their
immediate surroundings
updating all the information (in excess of 50KB/sec)
around each of the players’ units all the time may be
impractical
Bottom line: only update what needs updating
Additional Processing Problems
Huge computational demands for AI
both for players and for the computer adversaries
needed to act against these players
typical virtual worlds might include millions of AI
units
Huge computational demands for path-finding
large maps needed to house thousands of players are
problematic for standard path-finding techniques
Data consistency
across multiple servers
all connected clients
can get very complex
World Segmentation
To save on data transferring
Divide the world into small square regions
each region must be bigger than the highest line of site
radius
don’t worry about info that can’t be seen
for each region, keep track of:
all the elements in the region
all the players who should receive information about that
region
players viewing the region
Crossing Regions
World segmentation on the server before and after unit A in
D4 crosses to E4.
The gray areas are regions marked as viewed for the player
who owns units A.
Units that belong to other players are marked as b (viewed),
x (not viewed).
Alternative: Selective Continuous Updating
World segmentation on the server before and after unit A in D4
crosses to E4
The light gray areas are regions marked as viewed for the player who
owns units A
Light gray are CU (Continuously Updated)
Dark gray are PUR (prediction used)
Approach for Maintaining Data
for (each region of map R) do {
for (each connected player P viewing region R) do
for (each element E in region R)
Create message updating element E’s state
}
for (each connected player P) do {
Compress all messages to player P
Send messages to player P
}
This gets complicated for RTS when a player’s units may
be scattered over multiple regions
MMO Architecture
Client/Server dominates
implementation requires scalability, reliability, and
speed
also requires measures to enforce subscriptions and
prevent cheating
Plus a database. For what?
world info (ever changing)
game state
player/character info
MMORPG Communications Example
Ex: a player wants to strike an enemy with a sword
1. Player sends an action message to the game server
• communicates that player wants to "strike" an enemy
• at this point, the player cannot send further messages until this message including ALL of the packets that comprise it - is received by the server,
processed by the game engine, and an update message sent back to the player
• the moment a player's PC initiates an action, the PC is locked up until the
above scenario plays out
2. Server receives message in queue with messages sent from
hundreds, or thousands, of other players
3. The server’s game engine deciphers the action message and
calculates the necessary information to determine the outcome of
the action "strike with sword."
• the engine will consider many factors, including the statistics of the player
and the enemy, the properties of the sword, etc.
4. The game engine determines the outcome and communicates this
event to the player, along with all potentially affected players
5. The player and his or her fellows will now experience the action as
it is displayed on their computer screens
More Saving on Data Transfer
Only update game state data that has changed
Only update position if it changes and the velocity
changes
each client can use dead reckoning reliably otherwise
Additional Issues to Consider
Game Lobbies
Subscriptions
Virtual Economies
Cheating
Farming
Game Lobbies & Subscriptions
Client/Server of course
Middleware opportunity
uniform expectation for all games
players don’t come back for more because of the lobby
Ex: Gamespy
can support hundreds of thousands of players
searching for games
enable chat & voice
tournaments, ladders, etc.
automatic game patching
etc.
Virtual Economies
More an more games encourage trade
Some even use currency
Ex: Second Life
Creates a game within a game
Can help build communities
Player accounts have additional security concerns
in such games
government regulation seems inevitable on some level
virtual taxes?
Cheating
Can ruin a gaming experience
Comes in so many forms, sometimes there is no
programming solution to prevent it
when action is taken outside the virtual world
Game performance vs. Cheating prevention
Pure Client/Server vs. Hybrid
Encryption vs. Plaintext
Categories of Cheating
Exploiting Misplaced Trust
tampering with client side code
ex: map hack
Collusion
common in card games
Abusing the Game Procedure
I’m losing so I’m quitting or slowing down
Abusing Virtual Assets
not paying for acquired assets, using farms
Exploiting Machine Intelligence
using Deep Blue on Yahoo chess
Categories of Cheating (2)
Modifying Client Infrastructure
changing a graphics driver to ones advantage
ex: to see through walls, “wall hack”
Denying Service to Peer Players
flood an opponent’s network connection
Timing Cheating
Delay moves until opponents moves are known, “look ahead
hack”
“suppress correct cheat”, purposely drop update messages at the
right time
Compromising Passwords
roam around looking for newbies
tell them you are the administrator and need their password
hope they are 12 years old and dumb
Categories of Cheating (3)
Exploiting Lack of Secrecy
sniffing unencrypted data
Exploiting Lack of Authentication
setting up a bogus game server
re-authenticate idle players – issues at Internet cafes
Exploiting a Bug or Loophole
farming
gameplay for some vs. cheating for others
Compromising Game Servers
hack a server, screw everything up
Related to Internal Misuse.
evil employees
Farming
A player kills monsters in the game for the money and
items that the monster drops
Players who farm usually:
camp an area
kill monsters as they spawn
collect the loot
sell the items to others
Sweatshop farming in:
China, Mexico, and others
see http://www.1up.com/do/feature?cId=3141815
Other MMO terms:
loot whore
twink
zerging
What else?
MMOFPS
not many so far
Ex:
World War II Online (2001)
PlanetSide (2003)
Control Monger (2005)
Huxley (2006)
Lord of the Rings Online: Shadows of Angmar
http://lotro.turbine.com/
Want a job at Turbine Games in Westwood, MA?
http://www.cytiva.com/cejobs/templateTurbine.asp
References
A Systematic Classification of Cheating in Online Games by Jeff
Yan and Brian Randell
Addressing Cheating in Distributed MMOGs by Patric Kabus,
Wesley Terpstra, Mariano Cilia, Alejandro Buchmann
Alternate Reality: The history of massively multiplayer online
games. by Steven L. Kent
http://archive.gamespy.com/amdmmog/week1/
Analysis of Factors Affecting Players’ Performance and Perception
in Multiplayer Games by Matthias Dick, Oliver Wellnitz, Lars
Wolf
From sweatshops to stateside corporations, some people are
profiting off of MMO gold.
by James Lee
http://www.1up.com/do/feature?cId=3141815
More References
High Latency Multiplayer Gaming by Edward Hannay
John Carmack’s Blog
http://www.armadilloaerospace.com/n.x/johnc
Massively Multiplayer Game Development 2 by Gideon
Amir and Ramon Axelrod
MMO Demographics, Trends Explored in Survey
http://www.gamasutra.com/php-bin/news_index.php?story=6582
Networking Multiplayer Games by Sugih Jamin
http://ai.eecs.umich.edu/soar/Classes/494/talks/lecture-15.pdf
Even More References
On Virtual Economies by Edward Castronova
http://www.gamestudies.org/0302/castronova/
Online Game Architecture: Back-end Strategies By Dan
Esbensen
http://www.gamasutra.com/gdc2005/features/20050310/esbensen_01.shtml
Unreal Network Architecture
http://unreal.epicgames.com/Network.htm
Wikipedia
http://en.wikipedia.org/wiki/MMORPG