Jump to content
  • Advertisement


  • Content Count

  • Joined

  • Last visited

Community Reputation

1862 Excellent

1 Follower

About Drew_Benton

  • Rank

Personal Information

  • Role
  • Interests

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. Drew_Benton

    The New GDNet+ - No Ads!

    Great new simple structure and benefits for the price! I'm glad to be able to go into the new year soon supporting GDNet this way. Thanks!
  2. The download in the first post is broken. Do you mind fixing it or posting a download link to it somewhere? Thanks. 

  3. Hey Benton,

    This is Halim. I was reading your post "A guide to getting started with boost::asio".

    But I couldn't locate the option to download the zip file.

    Can you please tell me how can  I get the zip file.

    I would appreciate that.

    thanks a lot.


  4. Hei. I am just curious. Are you the same drew benton who created the tools for silkroad? And btw, you can't receive any new PMs :)
  5. Drew_Benton

    Looking to kill IOTD as it currently exists.. Need testers

    Talk about a trip down memory lane! I still have (and cherish) my trading card: [spoiler] [/spoiler] Anyways, Michael, I started clicking through the showdown and I don't particularly like the format. The best explanation I have to why I feel that way comes in the form of a question: "Do the screenshot necessarily need to compete with each other, or should a screenshot only compete with itself to the viewer?" I think a "vote/no-vote" system would be more appropriate for the screenshots. Either the screenshot is such that it invokes a viewer to "vote" for it, thus giving it a point, or "no-vote" it and go to the next screenshot. With that sort of system, the screenshots that are appealing for whatever reasons will bubble to the top with votes, while those that don't simply "don't have votes", which is not negative, just not positive. For something that is supposed to be fun and entertaining, I think a model like that one would better suite the screenshots while not taking anything away from the screenshot itself.
  6. Drew_Benton

    My First try in HTML5 game

    I found Level 6 to be pretty tricky compared to all other levels around that set. Level 12, 13, and 14, you don't extend the blocks at the top off-screen, so you can just aim straight up and shoot over easily, bypassing the challenges. The pineapples and their vision mechanic don't make the game any more challenging; they just waste the time it takes to fire your one shot. That mechanic needs to be reworked. Level 23, you can't zoom out far enough really. The text covers a top block and that's a little annoying. I played through all 24 levels, but the game just went to the title screen after completion. So there's no end game credits or "you won" message. That makes it feel like an incomplete game. Overall, it's a cute little game, but too repetitive, not enough mechanics to make it challenging. There's pretty much only one way to solve most of the puzzles and it's more based on consistent timing than anything. I think it needs more varied music as well. You always start out on the left side of the screen and your objects are on the right. Just an observation. Nonetheless, congratulation on your first HTML5 game! It's a really good start, but there's a lot more work to be done on it. Good luck!
  7. Drew_Benton

    Software patents

    Seems like this won't be an issue. [/quote] It still is an issue, and it will always continue to be one for any oss project threatened with patent violations. If you accept him saying that, then you are operating under the assumption the project actually does violate the patent (or admitting it did violate the patent). Just because he thinks the project violates his patent, doesn't mean it actually does; that is for the legal system to decide. Looking past that important point, will that statement on a blog be upheld in a court of law a legally binding agreement? I think not, but that's not up to me to decide. There needs to be two sides to the agreement. What does it mean to be a part of the open source community? Which one (there are public and private ones)? What about commercial usage? There's too many questions to simply take that at face value and think it's "ok" now. Maybe he changes his mind, maybe he sells the patent to someone else who has a different opinion, or maybe he means it, and won't ever take action. Who knows, it doesn't matter. What does matter is that before you use the library, or any library for that matter, you have to be aware of patent issues and be able to handle them accordingly. In this specific case, it's been shown that you might run into patent issues, so you will have to plan for the worse and seek legal counsel if you really want to be sure. FWIW: I think Doug Rogers got the short end of the stick here. Looking at the released initial e-mail, I think it was pretty civil, done in a respectful matter, and in a way that was not meant to have things blown out of proportion. But what about the title you might say? Well it's an appropriate title to ensure the e-mail gets read. If I saw an e-mail with that title in my inbox, I'd surely click on it. But as with anything on the internet, things tend to get blown out of proportion way too easily. It's not like he was threatening a lawsuit in the shown e-mail or had actually filed a lawsuit, he seemed to want to try and talk things out and now look where that got him. It really sends a bad message because perhaps people might feel less inclined to try and open a dialog in the matter rather than just rushing straight into a lawsuit. Compare the e-mail Rich got vs the one Notch got. Which would you rather...? Anyways, I'm just commenting about the specific stuff at hand rather than patents in general. There's no need to beat a dead horse; the patent system needs to be drastically overhauled when it comes to software.
  8. Based on your other thread, I'd strongly urge you to slow down and actually work out you current problem rather than rushing to potentially solve the wrong one. The alternate asynchronous pattern SocketAsyncEventArgs provides is a very advanced model that caters to very specific needs. When they (Microsoft) say the model is for "specialized high-performance socket applications", they mean a very specific thing, not a general thing that you are thinking about. The model is meant to help developers control almost all aspects of resource costs for servicing 1000s, 10s of thousands, to even 100s of thousands+ worth of concurrent connections or an extremely high network I/O throughput. If you do not properly implement all aspects of this model, your solution essentially degrades into the same model provided by the Being/EndXXX API, just more complicated and bug filled. There's more to using the model than just the networking aspect. The rest of your code is vital in determining whether or not the networking can even scale to its max potential on the hardware you provide. The most basic and specific example is "global shared state". The more "global shared state" you have, the less efficient async models become due to locking. While there are certain ways around this, it is a very advanced topic. What's the point about talking about all this? The point of using this model is that you control all aspects of it. You would be hard pressed to find a generic socket server library that utilized SocketAsyncEventArgs because of how specialized the solution is. Whatever you might find, you certainly wouldn't want to use without understanding the core concepts first because typically speaking, you will be finding unsupported code that will have tons of bugs in it that will negatively affect your application down the road. If you needed a library that did all of this for you, then use the Begin/EndXXX API! The bigger issue at hand though is that if you are having issues with the Begin/EndXXX API, the XXXAsync API functions will not magically solve your problems, especially if you do not understand what the problems are in the first place. That is why you need to try to figure out the real problem first. If there's one thing I've learned over many years of working with networked applications is that there's nothing worse than solving the wrong problem using an even more complicated solution because you did not take the time to understand the inherent flaws in your code. You should really post code in your other thread if you want to get more help as right now, all people can do is guess. Programming and guessing do not go together, especially if you hope to get a problem solved.
  9. In the past, I've made a few simple games and I've made a few simple engines. Nothing commercial, just indie stuff. I hope this doesn't sound too cynical, but it's the truth. I started out on GameDev back in 04-06 with aspirations to become a game developer. Unfortunately, I got caught up in the whole "making engines rather than games" deal. Ultimately, it lead to the demise of my game development career and I moved on at the time. I'm not a person with regrets, but if I knew now what I did then, I'd have not wasted my time. The matter of the fact is, a game engine isn't an end, it's the means. But, you have to ask yourself the means to do what? If you want to make a game engine to understand how game engines work, there are far superior ways, such as studying and using existing successful game engines, whether they are commercial or not. I'm a strong believer in trial and error, but in terms of a time investment, getting experience and actual portfolio end product work on commonly used engines looks and feels a lot better than unpolished tech demos on an engine that you might think is great, but everyone else just shrugs at. Don't believe me? Just take a look at some job offerings for "engine programmer/developer". I'm not going to link specific postings, because it might feel a bit like advertising, but hopefully you'll get the idea. Having your own experience is not bad, but the way you do things certainly won't always be the way the "industry" does things. If you want to compete in the "industry", you have to play their game. Even if you don't want to get into the industry, part of becoming a good programmer is finding the right tools for the job. The sooner you get over the hump of trying to do everything yourself, the sooner you can actually make your dreams come true and get stuff done. If you want to make a game engine to make games, then you should really just make games. Here is the obligatory, Make games, not engines article. The entire read is good, but the third from last paragraph is what I want to draw the most attention to: [background=rgb(250, 250, 250)]Most hobby developers who “finish” an “engine” that was designed and built in isolation (with the goal of having an engine, not a game, upon completion) can’t ever actually use it, and neither can anybody else. Since the project didn’t have any goals, any boundaries, or any tangible applications, it essentially attempted to solve aspect of the chosen problem space and consequently failed miserably. ....[/quote][/background] Looking back now, as I know a lot more than I did in the past, this is exactly what happened to me, and most other people who went down this route. In a sense, this quote highlights the main problem most people have with "learning" anything. Trying to learn something as an "end" rather than as a "means" most typically leads down a hard and unsuccessful path compared to people who use it the other way around. Sure, there are exceptions, but that's why they are called exceptions. How should you view game engines? As a manufacturing factory whose sole purpose is to speed up the production of games. You wouldn't build a factory without knowing what product you are producing, right? Unfortunately, most people do when it comes to game engines and games. So my advice to you would be simple. Forget about the concept of "making a game engine", completely. As saejox mentioned, learn graphics rendering, physics, sound, input, scripting, multi-threaded programming, scripting, databases, tool development, etc... typical software development stuff applicable to game development. Once you learn those things, make games using them. When you have enough games made, you will see commonly recurring patterns of functionality and tools. Take all of that stuff and get it interconnected into a new project. You now have a game engine, without having made a game engine. From there, it's all about evolving the project as you continue to make more games from it. If you have made games already, great! You are ahead of most people who want to start their own game engine. However, you still need to keep making games in order to understand the type of engine that you need to help speed up game development of similarly typed games. Making simple board games doesn't mean you are ready to make a generic game engine for a FPS, RTS, or anything like that. If you have interest in developing a broad range of games, then focusing on an engine is not a good idea, as the game development concepts can vary between game genres (e.g., action based mmorpg vs turn based rts).
  10. What makes you think that you can't have your "initialize" function throw an exception? The concept of return codes is just one of the two ways to implement two step Initialization. If you prefer one step initialization, great! But why? If you believe exceptions make for cleaner code, and throwing an exception from an initialize function is perfectly valid and typical of C++ exception styled programming, then you haven't made an argument for either yet. Poorly constructed exception handling is no better than poorly constructed non-exception handling either, so saying you have a "well defined shutdown of your application" is not always true. What SiCrane said about "This isn't a one-size-fits-all situation." is pretty much the main focus point that should be addressed. Looking past exceptions, which is only one of the main aspects to this issue, the cost of "creation, copy, and destruction" have to be kept in mind as well. How expensive is it to create, copy, or destroy your objects? Are your objects going to need pools for managing memory? It's just going to depend on a case by case basis, thus there is no one-size-fits-all solution. Furthermore, why choose one or the other when both might be more appropriate? Resource Acquisition Is Initialization, RAII, is one such idiom where inherently it is one step initialization, but there are times when adding support for two step initialization can make for more flexible and simplified code. A specific example would be Win32 critical sections (whether you use them or not isn't important as much as understanding the justification). Rather than littering your code with Enter/LeaveCriticalSection calls, you can use RAII to greatly simplify the process. However, there might be times when you need the concept of RAII, but the implementation doesn't make logical sense. E.g., acquiring exclusive access to a CS, but not needing to maintain that access at all times (to prevent deadlocks), so allowing for two step initialization with manual cleanup code support helps keep things more simple/cheap than constructing/destructing new objects over and over. It's typical in game development, and most other development, to make uses of 3rd party libraries at one point or another. Maybe it's a mysql++ connector wrapper, or a physics library, or an input or audio library, the list goes on. While a lot of people have a DIY mentality, it's important to understand that you can't simply reinvent the wheel for everything and will eventually have to resort to another person's code. A lot of these libraries might be setup to use exceptions, while some might not. In either case, you have to design your code around how the other components are setup. This means, specifically to the OP, you should not be trying to "commit" to one style or another, especially in a language like C++. It's like saying you want to have dinner tonight, but don't want to eat a meal that would require the use of a fork. To each their own, of course, but it's certainly not a typical concern from that perspective to say the least.
  11. Drew_Benton

    Am I "using" people?

    I am not a lawyer and not trying to provide the following as legal advice, but here's something to think about. Ultimately, I don't think it's an issue that boils down to morals or ethnics, but rather simply legal. If you try to hide what you will be doing with user contributions, you are more likely to be viewed negatively in the eyes of the community, so I would suggest being more upfront with your plans rather than hiding them away in a legal document. I digress though. You should also need specific terms that apply to the process of "content submission" in addition to the normal terms applied to the game/tools themselves. In regards to the latter, your terms should say what people can or can't do with the content they create with your tools. E.g., if you provide people with a level editor, clearly specify if they can only use it for non-commercial purposes, if they are allowed to re-distribute the content, and so on. There's a lot to consider there and it's handled a number of different ways in different scenarios. In regards to the former, you open up another can of worms when it comes to accepting user content, especially if you plan on publishing it or redistributing it in any form. For example, and I'll use an excerpt from the GameDev.net Terms of Service: c) Customer warrants to Provider that Customer has all necessary rights to store, reproduce, license access to, and otherwise use the data contained in each of the Customer posted content for which Customer utilizes Provider's Software and Services. [color=#5A5A5A][font=helvetica, arial, verdana, tahoma, sans-serif]d) Customer acknowledges that Provider's software stores customer data, personalization settings, and other Customer posted content. Customer hereby grants to Provider a fully paid up, non-exclusive license to store and maintain such data for the limited purpose of providing a public forum.[/font] [/quote] 'c' is vital in terms of ensuring users have the necessary rights to provide the material and 'd' is vital in establishing what that material can be used for once GameDev.net has it. If you look up the ToS for any game publishing platforms or application stores, you will see similar. Some sites reserve the right to feature or use your stuff for purposes of promoting their site and so on. It should be noted though, you are still ultimately responsible for the content, even if someone breaks your ToS to provide you with it. In other words, since you are accepting user created content, even though it is done with your tools, there are still "rights" issues that have to be considered. If your levels allow people to supply their own textures or models, then you would need to ensure those textures and models are not being used from a rights violations. Perhaps specific level designs are made that would infringe on trademarks or one thing or another. There's a lot of considerations. In either case, you are setting yourself up for a lot of potential legal problems if you simply use user contributed content directly in your game. You would have to verify and ensure you have all the necessary rights to use the content first, which in itself, might be too much work to be worth it, to avoid issues down the line when someone sees their stuff in your game. People obtaining and using content that contains rights violations is a totally different issue, out of your control (from a non-technical standpoint, e.g., not having DRM mechanics built in). If I were you, and you were worried about these things, you simply don't bundle any user contributed content with your game. You create a website that allows for people to share and download maps, taking into consideration DMCA provisions and the steps necessary for addressing copyright complaints so you are fulfilling your legal obligations. Here is one such page (random, no affiliations) that will give you an idea about that: Reducing Company Website Liability - Steps to Verify DMCA Safe Harbor Compliance. That way, if anyone has any copyright claims, they need to follow the process and give you the appropriate time to respond vs. just sending out a C&D or filing a lawsuit for the violations. Here is another page (random, no affiliations) that cover this as well: How to send Cease & Desist and DMCA Takedown letters to sites infringing your copyright. Of course, a lot of these things depend on how your actual level editing pipeline works. If you are talking about a 2D game with a fixed number of sprites to use, and it's a matter of a map format that uses only numbers to represent the tiles and users cannot add any custom images or sounds, then you won't have to worry about hardly any of these things. In that case, it's simply a matter of establishing the terms of what you can do with the content once a user submits it to you. On a side note, and I'm sure you are familiar with the game, StarCraft 2 took quite an interesting path when it comes to content creation by keeping everything server sided. Even with that model though, they still have to maintain a clear copyright infringement policy consistent with what was previously mentioned. And as always, you should consult a lawyer!
  12. Drew_Benton

    Can't type "}" in Visual C++ 2010

    Here's something you can try, not sure if it'll work: 1. Download and install AutoHotKey: http://www.autohotkey.com/ 2. Create a new AHK script and paste in the following contents: #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. #Warn ; Recommended for catching common errors. SendMode Input ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory. ::}::{}} 3. Save and then execute the script (you will see a green H icon in your tasktray if it's running). To stop the script, right click on this icon and choose the appropriate context item. 4. Try using the } key in Visual Studio followed by another key to trigger the macro. For example, press } and then 'enter' or 'spacebar'.. The idea is to make use of Hotstrings to replace the keystroke itself with the text. With how AHK works, it should process the } before Visual Studio does (assuming Visual Studio is in fact eating the keystroke) and you should get the text to show up after the followup key stroke to trigger the macro. Do you have any addons installed in Visual Studio? Perhaps a bug in one of those is causing a problem. You should also check your system for any system wide hooks or DLLs being loaded in AppInit_DLLs. Perhaps there is something that isn't compatible with Visual Studio, but is working fine with everything else.
  13. Drew_Benton

    Diablo 3 representing the future of Anti- piracy?

    I think most people misunderstand what Diablo 3 and Batle.net 2.0 are. Chindril seems to have an important part of it down, but didn't really elaborate to the topic at hand, so I will. I'm not going to try to change anyone's opinion on the matter, but hopefully more people can see things how they really are rather than what they are perceiving them to be. To start out, I'll list some points of interest that my explanation is based upon. I'm not going to fully elaborate each point, but just give enough for readers to hopefully see where I am going with it. 1. DRM simply does not work for the masses. Short term or long term, it's been shown time and time again. In the end, the paying customers suffer the most, while the illegitimate users benefit the most. Some companies are finally getting the picture, while some are not. 2. Writing the functionality for a single player version, a multiplayer version, and a lan version of a game, in addition to the multiplayer server, is impractical when all you have to do is write a multiplayer client and a multiplayer server (more on this later). 3. In this digital age, selling digital products has been increasingly more difficult due to piracy. The business model of selling digital goods is going down the drain. The foreseeable viable alternative is to sell access to a service instead. 4. We, as a society, are experiencing a digitally driven social revolution. Facebook, twitter, reddit, and many other services are now a part of everyday life in ways that social media never was imagined a decade ago. Now, how are all these points relevant to the discussion at hand? Consider if you were Blizzard: "If we write a single player game, it will get pirated and we will lose money. If we add DRM, we will be vilified and cause even more people to pirate the game." "If we write a SP/SP-LAN/MP version of the game, we are doing a lot more work and have a lot more security concerns as we did with D2, which also will cause us to lose a lot of money" "if we don't legitimize official item selling via RMAH, someone else will capitalize on the market, like in Diablo 2, and that money will not be going to us." "We need a way to add social elements to the game to stay relevant and allow people to enjoy the game with friends easily." The only solution is a client-server model for the game. Let's eliminate single player altogether so people have nothing to crack/pirate. Cut down on all the extra security and maintenance required for SP/SP-Lan/MP versions of the game so we only have to deal with a non-authoritative client and an authoritative server. Let's add a GAH/RMAH so people can safely do what they always wanted to while allowing us to capitalize on our own IP. Sure, people will go outside our system, but our system will be of the most safe and convenient for users. Finally, let's add some more social features to the game via Battle.net 2.0. Friends should be able to easily join each others games at the click of a button. Match making should be seemless and require no effort for people to join new games and complete quests with strangers. This is what I truly think Blizzard's logic was for the design of Diablo 3. To maximize profits, minimize costs, and be in as much control as possible over their game. Isn't that the ultimate goal of any business? I can't say I blame them for trying to financially survive in these times. With all that being said, the designs of Diablo 3 and Battle.net 2.0 are not so much about anti-piracy as much as just being the one stone that kills many birds, so to speak. It's not a silver bullet, obviously, but it addresses the main concerns with making a new blockbuster game and I think it is the future of major games. However, where Blizzard has failed is the actual implementation of everything I just said. I was a part of the beta since late last year. Each major test had the same connectivity issues experienced on login. Quite literally, they had the same problem for at least 6 months and were unable to fix it by the time of launch. The launch day problems did not surprise me, but given the amount of time Blizzard had to address the problem, obviously they failed pretty hard. Likewise with random disconnects, another issue that was going on since beta. Next, the state of their GAH is just a mess. I find it totally unacceptable, after all this time and testing that they have to take 1/2 of it down and rework it while the other 1/2 is unstable the majority of the time. To think that the RMAH was going to work in the same way, I see now why it has been delayed for a while, which is totally disappointing, all things considered. I don't expect anything to be flawless, but I do expect a certain level of quality in a game like this, and that level has not been met. Their "social" aspects of the game are just quite pitiful. Their match making is akin to blind or speed dating. You get no choices on who you might get grouped with, group sizes were low for a while, and trying to play the game with randoms who had really bad gear is no fun at all. I can't tell you how many times I joined people who had 6k hp in Hell with hardly any resists, and had to carry them through everything. Have you ever been in a group with all of the same class? It can be quite annoying. When I play my Witch Doctor, I prefer to be in a group with a Monk or Barb at least. If I play my wizard, I'd like to be with a Barb or Witch Doctor. So on and so forth. Their biggest mistake though, is failing to establish a real identity for the game. The name "Diablo" is what carried the game. So much changed in the beta from the time I started trying it until May when it shut down from launch. PvP was shelved and who knows when that will be added. The AH, as mentioned before, is a mess. The state of Inferno and the itemization of items in game show clear design flaws that make you ask, "what were they thinking?" Honestly, it feels like they ran out of time and had to put out something for the money, and will be spending the foreseeable future, "finishing the game". I myself hated the beta with a passion. I thought I'd never play the game based on what I saw. However, the idea of the RMAH intrigued me and I'm a sucker for the "Diablo" title, so I decided to give it a go. I figured I could play a little and when the RMAH comes out, see if I wanted to stick around or not. With the way things have worked out now though, I've stopped playing and will be awaiting the 1.0.3 patch. I've gotten 3 different classes to 60 (which is pretty easy with how the game is setup), but with the way items work and how Inferno is designed (don't get me started on all the flaws and exploits), the game is not only unplayable, but simply unejoyable now. I don't regret the $60 purchase, but after all this time and knowing what types of resources Blizzard has, I find Diablo 3 to be quite disappointing, which is a shame because there's a lot of really nice things about the game that gets overlooked and not talked about either.
  14. I think you need to start over with the code you are working with and restructure it. When you work with TCP, it's far easier to think in layers when working with the data. The lowest layer is the raw byte stream you send and receive. At this layer all you are worried about are bytes and making sure you send and receive them. What the bytes represent is totally irrelevant; all you care about is making sure they are processed correctly by the system. The next layer up is your protocol layer. This layer gives meaning (but not context) to specific bytes and determines how data is processed by the system. For example, using "§" as a delimiter defines your protocol. You know messages begin from the beginning of the stream until a "§" is received. Finally, the message layer is on top. This layer gives context to the data passed using the protocol. In your case, you only have one type of implicit message, text, but you could expand your protocol to support other types of messages as well. For example, add more delimiters that would result in different processing of the data. I.e., let's say you use "[" and "]" to make a section of text that should be capitalized, that'd be part of the protocol while the ability to "bold" text is part of the message itself.. When receiving data, the process is [Raw Bytes] -> [Protocol] -> [Message(s)]. When sending data, the process is reversed: [Message(s)] -> [Protocol] -> [Raw Bytes]. This means your send/recv logic should be generic, protocol agnostic, and completely reusable for any program really. Since you are working with TCP, and TCP is a stream protocol, you have to make use of buffering. At this point in your learning and programs, you do not have to be worried about the extra overhead from data copies or allocations or anything like that. You just want good solid code that works and you can understand. You will need to buffer all data you receive at the lowest layer and then allow the next layer to process it separately. Once the protocol layer is done processing it, it reconstructs the messages and buffers those for the system to process. When you go to send data, the reverse happens. You buffer a higher level message first, then let the protocol layer break down the messages into byte buffers, then dispatch the buffers to the raw processing layers. Putting all this together, here's a simple single threaded, one client example that shows the distinctive separation of the layers. Only the important stuff is commented. [spoiler] [source] #include <winsock2.h> #include <mswsock.h> #include <windows.h> #include <stdio.h> #include <string> #include <vector> #include <list> #include <iterator> #include <algorithm> #pragma comment( lib, "ws2_32.lib" ) int main( int argc, char * argv[] ) { WSADATA wsadata = {0}; int error = 0; error = WSAStartup( MAKEWORD( 2, 2), &wsadata ); if( error != 0 ) { printf( "WSAStartup failed with error (%d).\n", error ); return -1; } if( LOBYTE( wsadata.wVersion ) != 2 || HIBYTE( wsadata.wVersion ) != 2 ) { printf( "WSAStartup does not support version 2.2.\n" ); error = WSACleanup(); if( error == SOCKET_ERROR ) { printf( "WSACleanup failed with error (%d).\n", WSAGetLastError() ); } return -1; } SOCKET listener = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if( listener == INVALID_SOCKET ) { printf( "socket failed with error (%d).\n", WSAGetLastError() ); return -1; } sockaddr_in localAddress = { 0 }; localAddress.sin_family = AF_INET; localAddress.sin_addr.s_addr = inet_addr( "" ); localAddress.sin_port = htons( 7777 ); error = bind( listener, reinterpret_cast< sockaddr * >( &localAddress ), sizeof( localAddress ) ); if( error == SOCKET_ERROR ) { printf( "bind failed with error (%d).\n", WSAGetLastError() ); closesocket( listener ); error = WSACleanup(); if( error == SOCKET_ERROR ) { printf( "WSACleanup failed with error (%d).\n", WSAGetLastError() ); return -1; } } error = listen( listener, 1 ); if( error == SOCKET_ERROR ) { printf( "listen failed with error (%d).\n", WSAGetLastError() ); closesocket( listener ); error = WSACleanup(); if( error == SOCKET_ERROR ) { printf( "WSACleanup failed with error (%d).\n", WSAGetLastError() ); return -1; } } sockaddr_in remoteAddress = { 0 }; int remoteAddressSize = sizeof( remoteAddress ); SOCKET client = accept( listener, reinterpret_cast< sockaddr * >( &remoteAddress ), &remoteAddressSize ); if( client != INVALID_SOCKET ) { printf( "Accepting a connection from %s:%i.\n", inet_ntoa( remoteAddress.sin_addr ), ntohs( remoteAddress.sin_port ) ); u_long mode = 1; error = ioctlsocket( client, FIONBIO, &mode ); if( error == SOCKET_ERROR ) { printf( "ioctlsocket failed with error (%d).\n", WSAGetLastError() ); } else { std::list<std::string> incomingMessages; std::list<std::string> outgoingMessages; std::vector<char> sendWorkspace; char recvBuffer[8192]; std::vector<char> recvWorkspace; bool checkRecvWorkspace = false; // Client welcome message. outgoingMessages.push_back( "Welcome!\r\n" ); while( true ) { //--------------// Protocol processing logic (send) //-----------------------// if( !outgoingMessages.empty() ) { std::list<std::string>::iterator itr0 = outgoingMessages.begin(); while( itr0 != outgoingMessages.end() ) { std::string & message = *itr0; message += '§'; std::copy( message.begin(), message.end(), std::back_inserter( sendWorkspace ) ); ++itr0; } outgoingMessages.clear(); } //--------------// Raw data processing logic (send) //-----------------------// if( !sendWorkspace.empty() ) { int count = send( client, &sendWorkspace[0], sendWorkspace.size(), 0 ); if( count == SOCKET_ERROR ) { error = WSAGetLastError(); if( error != WSAEWOULDBLOCK ) { printf( "send failed with error (%d).\n", error ); break; } } else { sendWorkspace.erase( sendWorkspace.begin(), sendWorkspace.begin() + count ); } } //--------------// Raw data processing logic //------------------------------// int count = recv( client, recvBuffer, sizeof( recvBuffer ), 0 ); if( count == 0 ) { printf( "Disconnected.\n" ); break; } else if( count == SOCKET_ERROR ) { error = WSAGetLastError(); if( error != WSAEWOULDBLOCK ) { printf( "recv failed with error (%d).\n", error ); break; } } else { std::copy( recvBuffer, recvBuffer + count, std::back_inserter( recvWorkspace ) ); checkRecvWorkspace = true; } //--------------// Protocol processing logic //------------------------------// // Since it is possible we get some data that is not complete, we only need to check // the workspace once it "changes". Otherwise, since we are in non-blocking mode, we // would be performing the same redundant checks each loop on data we already know // is incomplete. if( checkRecvWorkspace ) { checkRecvWorkspace = false; // Loop while we have raw data to process. This is so we can extract as many // messages at once rather than just one at a time per loop. while( !recvWorkspace.empty() ) { std::vector<char> message; for( size_t idx = 0; idx < recvWorkspace.size(); ++idx ) { if( recvWorkspace[idx] == '§' ) // alt + 167 in console { // Extract the message. std::copy( recvWorkspace.begin(), recvWorkspace.begin() + idx, std::back_inserter( message ) ); // Remove the message and delimiter from the workspace. recvWorkspace.erase( recvWorkspace.begin(), recvWorkspace.begin() + idx + 1 ); // Do not continue checking. break; } } // We only need to continue if we actually have a message to process. if( message.empty() ) { break; } // Make a null terminated string. message.push_back( '\0' ); // TODO: Verify message data, invalid characters, etc... // Save the message for processing by the system. incomingMessages.push_back( std::string( &message[0] ) ); } } //--------------// Message processing logic //-------------------------------// // Check to see if we have any messages to process. I check empty // to keep scope space clean of extra variables. if( !incomingMessages.empty() ) { bool doExit = false; std::list<std::string>::iterator itr0 = incomingMessages.begin(); while( itr0 != incomingMessages.end() ) { std::string & message = *itr0; // Simple command handling example. if( message == "exit" ) { doExit = true; break; } else if( message == "hello" ) { // Note how we simply save the higher level message to the list // and let the protocol processing logic take care of the rest. outgoingMessages.push_back( "world!\r\n" ); } else { printf( "Error: Unprocessed message: %s", message.c_str() ); } ++itr0; } incomingMessages.clear(); if( doExit ) { printf( "Client is exiting...\n" ); break; } } // Prevent 100% CPU usage in this example. Sleep( 1 ); } } error = shutdown( client, SD_BOTH ); if( error == SOCKET_ERROR ) { printf( "shutdown failed with error (%d).\n", WSAGetLastError() ); } error = closesocket( client ); if( error == SOCKET_ERROR ) { printf( "closesocket failed with error (%d).\n", WSAGetLastError() ); } } else { printf( "accept failed with error (%d).\n", WSAGetLastError() ); } error = closesocket( listener ); if( error == SOCKET_ERROR ) { printf( "closesocket failed with error (%d).\n", WSAGetLastError() ); } error = WSACleanup(); if( error == SOCKET_ERROR ) { printf( "WSACleanup failed with error (%d).\n", WSAGetLastError() ); } return 0; } [/source] [/spoiler] In this trivial example, everything is "inline", but when you use this approach, you can wrap everything up into helper functions and classes/structures to keep things organized and support more than one client. Each "context" object will have a socket, a workspace buffer, and message queues. This way, no matter what underlying send/recv mechanisms you use, the message layer remains the same as well as the protocol layer. If you want to change up the protocol some, the other layers aren't affected and so on. You won't ever "send" or "recv" data directly, only indirectly through buffering. This way, you can properly handle the semantics of the TCP stream as well as gain some flexibility in your system. It takes some getting used to working with TCP and this approach, but in the long run, it helps make your system a lot more manageable compared to the direction you are going right now. Good luck!
  15. Drew_Benton

    Dealing with idle state on the server

    If you are using IOCP on Windows, then something is wrong with your current implementation because IOCP naturally solves this issue by design. In typical IOCP use, you create a bunch of network worker threads that all block on [font="Consolas, Courier, monospace"]GetQueuedCompletionStatus[/font], waiting for work. When there is no work, there is no worker thread execution because they are all blocking. That means nothing will be spin waiting or wasting CPU cycles in an infinite loop bounded by a Sleep/Ex call. The scalability aspect of IOCP comes from the fact when you need more processing power, you simply create more threads that sit on GQCS and assuming you have the hardware resources, everything just works without change to anything else (of course, you have to have designed code that scales, but that is another issue). If you have all your worker threads blocking on GQCP, the most obvious question is how do you exit worker threads? This is also really easy by design, since you just call [font="Consolas, Courier, monospace"]PostQueuedCompletionStatus[/font] with a user defined message that you process in the worker thread that signals the worker thread to exit and not loop back to the next call to GQCP. Likewise, for any other custom event handling, PQCS is used to give the next available worker thread work to do. To implement a generic worker thread event handling system, you could also make use of the [font="Consolas, Courier, monospace"][/font][font="Consolas, Courier, monospace"]QueueUserAPC [/font]function. In that design, you simply setup a pool of worker threads that all block infinity with a SleepEx call. When you have work to process, you call QUAPC with one of the handles of the worker threads so the work is processed in context of that thread. For more information on that topic, check out the Parallel Programming with C++, an older, but still revelant blog entry that has very useful information about some Win32 stuff. I wrote some stuff with IOCP and UDP a while ago that sort of pertains to these issues. I have learned quite a lot since, so some stuff I got right, but a lot of stuff I got wrong with my understanding (too much to go over). Nowadays, unless you absolutely have to stick to writing everything yourself, there are libraries out there that take care of all these things for you and make life a lot easier. Such libraries include ACE and Boost. Boost::Asio is the main library you would be looking to get into, but there are a lot of other Boost libraries you would make use of. I also wrote some boost::asio stuff not too long ago. Once again, some stuff I got right, some stuff I got wrong, so take it with a grain of salt. There is a lot of issues at hand that would have to be explained first before simply updating those works. Anyways, getting back to the issues at hand, taking care of the IOCP aspect will fix anything inefficient about the network related work. What it will not take care of is your main simulation loop that performs any system upkeep. You can either stick with the Sleep pattern to throttle when there is no work or you can redesign your system to be more scalable and asynchronous and make use of worker threads to handle execution of any pending work. For example, using boost, you would have at minimal two thread pools of worker threads. The first pool is for network related stuff only. The callbacks that execute should involve very little shared state so you should not be hitting any unavoidable bottlenecks from having to synchronize access to global shared resources. This means that most business logic processing does not take place in these threads, work is forwarded outside that system. The second worker thread pool is for everything else that needs to execute. The reason for separating them is to achieve a more flexible system rather than having to worry about longer running tasks from starving out other critical tasks. Such a design is taken by .Net in their ThreadPool design along with Async operations. In doing so, all threads are always blocking, waiting for work. When there is no work, there is no execution so you do not waste any resources. When there is work, then threads will process it as efficiently as your code is implemented and that is that, The only times you might need to use Sleep in such a design is when the overhead of starting a new async operation is higher than simply waiting and trying again for a limited number of times. For example, say you need to open a file. If your first attempt fails, you might want to loop a few times and keep trying rather than simply let the operation fail. Otherwise, you would be setting up a timer to execute a limited number of times and then have to continue execution when the file was opened that really complicates things. The downside to using boost is the resource/performance overhead you are trading for simplicity and convenience. In most cases, it is not a big deal, because you end up writing easier to maintain and understand code without having to worry about all the little annoying issues you otherwise would have to. However, some people have very specific needs and are unable to use such libraries due to licensing issues, but if that does not apply to you, then you should definitely check it out. That is not to say boost is not without its own quips, but there is a large community of support available.
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!