简体   繁体   中英

C++ Good practices for a client-server multiplayer game

Please note I'm new to both threading and WinSock.

For a college project I have to create a simple multiplayer game writeen in C/C++ using WinSock for communication and WinAPI threads to handle multiple clients (maximum of 4).

The game is pretty straight forward, players move their dots along the board and leave their traces behind. The player who managed to cover the biggest area in a given time, wins the game.

On the client-side application I'm running 2 threads. First one sends information about pressed keys to the server. Second one receives data from the server (coords of all the players) and draws the world.

On the server-side Im running 1 thread for each client to receive his input, then update his coords on server. There is also another thread that does the logic (check for collisions, check if player didn't go off the screen etc.) and constantly sends players coords to all the clients.

Im using blocking sockets on both sides.

I tested the game for 2 players, server and clients were all on different machines in the same network and as it turns out players experience noticable lags and do not move smoothly.

Is my approach totally wrong? What's the best way to create server and client apps for multiplayer game?

Sockets normally try to combine multiple small messages into one transmission to improve network efficiency. But this slows down transmission of most messages because they sit in a buffer for a while hoping to get some more data before transmission. This is the "Nagle algorithnm." You can try turning it off using SetSocketOpt with TCP_NODELAY. That should reduce latency.

For a few players on a local network you could consider a peer-to-peer communication scheme instead of using a server. Routing everything through a server at least doubles the communication delays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM