CSE 381 Advanced Game Programming Sockets. Programming with TCP Transmission Control Protocol Has...

51
CSE 381 Advanced Game Programming Sockets

Transcript of CSE 381 Advanced Game Programming Sockets. Programming with TCP Transmission Control Protocol Has...

CSE 381Advanced 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 WorldMMORTS: Massively Multiplayer Real Time

Strategy GameMMORPG: Massively Multiplayer Role-Playing

GameEverquest, Tactica online, Final Fantasy XI, etc.

Descendants of MUDs (Multi-User Dungeons)1979, Roy Trubshaw and Richard Bartle

Types of MMOs

MMORPGimmersive worlds

replace your own life with that of your own avatar

typically each player controls a single unit

MMORTSstrategy & quick thinking more important

typically each player controls dozens of units

units may be visible, though far awaythousands 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 CostsEverquest uses thousands of clustered server boxes

working together in a redundant networka server box may contain multiple CPUseach server can handle 200-300 playersadditional redundancies necessary as well

Continually tweak balance to avoid “dead servers”Other costs of course:

networking hardwaretrained personnelair conditioning

MMOs are a very expensive market to enterAs games get more popular, they get much more

expensive to maintainsmall 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 worldin 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 AIboth for players and for the computer adversaries

needed to act against these playerstypical virtual worlds might include millions of AI

units

Huge computational demands for path-findinglarge maps needed to house thousands of players are

problematic for standard path-finding techniques

Data consistencyacross multiple serversall connected clientscan get very complex

World Segmentation

To save on data transferring

Divide the world into small square regionseach 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 Datafor (each region of map R) do {

for (each connected player P viewing region R) dofor (each element E in region R)

Create message updating element E’s state}

for (each connected player P) do {Compress all messages to player PSend messages to player P

}This gets complicated for RTS when a player’s units may

be scattered over multiple regions

MMO Architecture

Client/Server dominatesimplementation 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 sword1. 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 changeseach client can use dead reckoning reliably otherwise

Additional Issues to Consider

Game Lobbies

Subscriptions

Virtual Economies

Cheating

Farming

Game Lobbies & Subscriptions

Client/Server of courseMiddleware opportunity

uniform expectation for all gamesplayers don’t come back for more because of the lobby

Ex: Gamespycan support hundreds of thousands of players

searching for gamesenable chat & voicetournaments, ladders, etc.automatic game patchingetc.

Virtual Economies

More an more games encourage trade

Some even use currencyEx: Second Life

Creates a game within a game

Can help build communities

Player accounts have additional security concerns in such gamesgovernment 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 itwhen action is taken outside the virtual world

Game performance vs. Cheating preventionPure Client/Server vs. Hybrid

Encryption vs. Plaintext

Categories of Cheating

Exploiting Misplaced Trusttampering with client side codeex: map hack

Collusioncommon in card games

Abusing the Game ProcedureI’m losing so I’m quitting or slowing down

Abusing Virtual Assetsnot paying for acquired assets, using farms

Exploiting Machine Intelligenceusing Deep Blue on Yahoo chess

Categories of Cheating (2)Modifying Client Infrastructure

changing a graphics driver to ones advantageex: to see through walls, “wall hack”

Denying Service to Peer Playersflood an opponent’s network connection

Timing CheatingDelay moves until opponents moves are known, “look ahead

hack”“suppress correct cheat”, purposely drop update messages at the

right time

Compromising Passwordsroam around looking for newbiestell them you are the administrator and need their passwordhope they are 12 years old and dumb

Categories of Cheating (3)

Exploiting Lack of Secrecysniffing unencrypted data

Exploiting Lack of Authenticationsetting up a bogus game server

re-authenticate idle players – issues at Internet cafes

Exploiting a Bug or Loopholefarming

gameplay for some vs. cheating for others

Compromising Game Servershack a server, screw everything up

Related to Internal Misuse.evil employees

FarmingA player kills monsters in the game for the money and

items that the monster dropsPlayers who farm usually:

camp an areakill monsters as they spawncollect the lootsell the items to others

Sweatshop farming in:China, Mexico, and otherssee http://www.1up.com/do/feature?cId=3141815

Other MMO terms:loot whoretwinkzerging

What else?

MMOFPSnot many so farEx:

World War II Online (2001)PlanetSide (2003)Control Monger (2005)Huxley (2006)

Lord of the Rings Online: Shadows of Angmarhttp://lotro.turbine.com/Want a job at Turbine Games in Westwood, MA?

http://www.cytiva.com/cejobs/templateTurbine.asp

ReferencesA 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. Kenthttp://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 Leehttp://www.1up.com/do/feature?cId=3141815

More ReferencesHigh Latency Multiplayer Gaming by Edward Hannay

John Carmack’s Bloghttp://www.armadilloaerospace.com/n.x/johnc

Massively Multiplayer Game Development 2 by Gideon Amir and Ramon Axelrod

MMO Demographics, Trends Explored in Surveyhttp://www.gamasutra.com/php-bin/news_index.php?story=6582

Networking Multiplayer Games by Sugih Jaminhttp://ai.eecs.umich.edu/soar/Classes/494/talks/lecture-15.pdf

Even More References

On Virtual Economies by Edward Castronovahttp://www.gamestudies.org/0302/castronova/

Online Game Architecture: Back-end Strategies By Dan Esbensenhttp://www.gamasutra.com/gdc2005/features/20050310/esbensen_01.shtml

Unreal Network Architecturehttp://unreal.epicgames.com/Network.htm

Wikipediahttp://en.wikipedia.org/wiki/MMORPG