📄 newbie.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"><html lang="en"><head><title>Winsock Programmer's FAQ: Information for New Winsockers</title><link rel="Stylesheet" type="text/css" href="./faq.css"></head><body bgcolor="#ffffee" text="#000000" link="#491e00" vlink="#7d2e01" alink="#da7417"><!-- ---- Header Bar ---- --><table border="0" width="95%" bgcolor="#006000" cellpadding="5" cellspacing="3" align="center"> <tr> <td align="left" bgcolor="#e0e0c0"> <font size="2" face=Verdana,Arial,Helvetica> <b><a href="general.html"><<</a></b> </font> </td> <td align="center"> <font face=Verdana,Arial,Helvetica color="#ffffee"> <p align=center class=bigger3><b> Winsock Programmer's FAQ<br> Section 2: Information for New Winsockers<br> </b></p> </font> </td> <td align="right" bgcolor="#e0e0c0"> <font size="2" face=Verdana,Arial,Helvetica> <b><a href="intermediate.html">>></a></b> </font> </td> </tr></table><!-- ---- Body Table ---- --><table width="95%" border="0" cellpadding="10"> <tr valign="top"> <td><a name="samples"></a><h5>2.1 - Are there any sample apps on the Net?</h5><p>Yes. There are several listed on the <ahref=resources/samples.html>Resources</a> page, and the FAQ's <ahref=examples/index.html>Examples</a> section has several more. If you'rejust getting started with Winsock, you may be especially interested in<a href="examples/basics/">these</a> samples.</p><a name="initwsadata"></a><h5>2.2 - Do I need to initialize the WSAData structure before calling WSAStartup?</h5><p>No, <code>WSAStartup()</code> fills this structure in for you.</p><a name="linkerror"></a><h5>2.3 - I'm getting link errors when compiling Winsock programs. What's wrong?</h5><p>You're most likely not linking with the proper Winsock importlibrary. For 16-bit Windows systems, this is winsock.lib. For32-bit Windows systems using Winsock 1.1 functions only, it iswsock32.lib. And for programs needing Winsock 2 support, you need tolink with ws2_32.lib.</p><a name="interop"></a><h5>2.4 - If I write a Winsock program, will I be able to communicate with a Unix sockets program?</h5><p>Absolutely! This common question is the result of confusing protocols with the APIs. Communicating programs need not have been created with the same APIs, as long as they are using the same transport and network protocols.</p><a name="langcompat"></a><h5>2.5 - Can I use Winsock with { My Favorite Language }?</h5><p>Most programming languages these days have some way of accessingWinsock, but Winsock is rarely used directly except from C or C++. Thereare several reasons for this.</p><p><b>Reason 1:</b> Some languages simply lack the languagefeatures to call the Winsock API. Your language needs the followingto fully use the Winsock API:</p><ol><li>Pointers. (The ability to access a specific piece of memory byits address.)<li>Bitwise operators. (The ability to change specific bits in a byte.)<li>Structures or records. (The ability to define a block of memory thatis an aggregate of simple data elements, such as two characters followedby a 16-bit integer. This feature must also allow some measure of controlas to how the data is laid out in memory.) </ol><p><b>Reason 2:</b> Many languages rely on some form of componentarchitecture (e.g. ActiveX) to provide outside services likenetwork access. Often the language environment comes with basicnetworking components, sufficient for most tasks. If your tool didn'tcome with the necessary compnents, or the ones it does come with aren'tpowerful enough, you may be able to find the functionality you need ina <a href="resources/libraries.html">third-party library</a>, rather thanwriting the necessary Winsock code yourself.</p><p><b>Reason 3:</b> Many newer languages <img src="./bitmaps/waist-dot.gif" alt="-" width=7 height=6 hspace=2> especially cross-platformscripting languages <img src="./bitmaps/waist-dot.gif" alt="-" width=7 height=6 hspace=2> include language support for networking.(Examples include Java, Perl, Python and Tcl.) From the programmer's pointof view, Winsock is rarely a concern when working in these languages.</p><p>For these reasons and others, this FAQ is <ahref=intro.html#langbias>biased towards C++</a>.</p><p>If your language allows direct access to the Winsock API, you maybe able to translate the C++ code in the FAQ into equivalent code inyour chosen language. However, I recommend that you look for samplecode in your chosen language via the <a href=resources/web-pages.html>WebPages</a> section of the FAQ, so you can study working code before youbegin translating.</p><a name="debugtools"></a><h5>2.6 - Are there any tools available for debugging Winsock programs?</h5><p>First, I would like to warn against using thebuilt-in Winsock debugging options, SO_DEBUG andthe dt_dll.dll. It'd be nice if these worked, but as <ahref="http://www.stardust.com/winsock/views/view_1999_09.htm">thisarticle</a> explains, it's currently so much of a mess that the toolsbelow work better for most people.</p><p>There are two categories of debugging tools: network analyzers(colloquially known as "sniffers") and Winsock shims.<p><p>Sniffers are usually software packages that run on one of the LAN'sworkstations and, due to the way typical LANs work, capture all of thetraffic going over the LAN. Good sniffers will also decode that trafficby various degrees. One advantage of a sniffer is that it literally seeseverything about the conversation, including low level protocol detailsthat aren't available from the Winsock layer. Another is that the goodones are extremely powerful and configurable. For example, some allowyou to write "protocol plugins" that will decode any protocol (such asa custom protocol that you've developed).</p><p>The disadvantages of sniffers are several:</p><ol><li>Software critics call a sniffer "inexpensive" when it costs less than$2000, and they positively gush when they cost less than $1000. Thisis because hardware sniffers, which are still quite common, are aboutan order of magnitude more expensive. <li>There are a few truly inexpensive sniffers, but many haveserious limitations: some have rotten or nonexistent user interfaces,few cheap/free sniffers run under Windows, and many are just plainweak.<li>Some sniffers only work on Ethernet, so they can't sniff conversationsgoing over PPP or other WAN links. </ol><p>All that aside, however, sometimes a sniffer is the only way to findout what you want to know about your program's behavior. If you've gotthe cash, a good sniffer is almost always the best tool for the job.</p><p>The other tool category is "Winsock shims." A shim sits between yourprogram and Winsock, either by replacing the DLL itself with a proxyDLL, or by "hooking" the Winsock DLL's API. These tools are limited tomonitoring events on the Winsock layer itself, and can only monitortraffic to or from a single host. (That is, they can't see the "bigpicture" of simultaneous conversations between many machines.) Theiradvantages are that this is usually sufficient, and that the mostexpensive shims cost less than $200.</p><p>The <a href="resources/debugging.html">Debugging Resources</a>page has links to several good sniffers and shims. Also, see <ahref="articles/debugging-tcp.html">Debugging TCP</a> for some less-automatedmethods of debugging a TCP program.</p><a name="errmsg"></a><h5>2.7 - How do I get a readable error message from a Winsock error number?</h5><p>The problem with this question is that it assumes that there is a"good" canned error message for every situation. The reality is that manytimes, you need to know the program's context before you can turn an errorvalue into a meaningful error message. For example, <code>WSAEFAULT</code>can mean "Bad pointer passed," or "Passed buffer too small," or even "Thatversion of the API is not supported." Since the Winsock spec documentsthe most likely error values that each function will return, you shoulduse this information to construct intelligent error handlers.</p><p>Still, sometimes an API call returns something unexpected, so a crypticerror message is better than none at all. In that case, you can justbuild a stringtable in your resource file mapping error numbers to errormessages. There is one such RC file for the Winsock 1.1 error values <ahref="ftp://metalab.unc.edu/pub/micro/pc-stuff/ms-windows/winsock/winsock-1.1/errno.rc">availablehere</a>. Alternately, the <a href="examples/basics">basicWinsock tutorial programs</a> in the FAQ include a utility module(<tt>ws_util.cpp</tt>) that defines a function for translating Winsockerror numbers into strings.</p><p>Note that some people will tell you that the Win32<code>FormatMessage()</code> API can be coerced into returning errormessages for Winsock error numbers. At best, this is undocumented behaviorthat only works with some implementations of Winsock. I personallyhave not been able to get it to work, despite significant time devotedto the problem. My advice is that you're much better off spending yourtime constructing meaningful error messages than chasing something thatcould never work very well even if it was documented behavior.</p><a name="wouldblock"></a><h5>2.8 - Winsock keeps returning the error <tt>WSAEWOULDBLOCK</tt>. What's wrong with my program?</h5><p>Not a thing. <code>WSAEWOULDBLOCK</code> is a perfectly normal occurrencein programs using non-blocking and asynchronous sockets. It's Winsock'sway of telling your program "I can't do that right now, because I wouldhave to <a href="glossary.html#blocking">block</a> to do so."</p><p>The next question is, how do you know when it's safe to tryagain? In the case of asynchronous sockets, Winsock will send you an<code>FD_WRITE</code> message after a failed <code>send()</code> call when itis safe to write; it will send you an <code>FD_READ</code> message whenit is safe to read after a failed <code>recv()</code> call. Similarly,in a non-blocking sockets program that uses <code>select()</code>,the <code>writefds</code> will be set when it's okay to write, and the<code>readfds</code> will be set if there is data to read.</p><p>Note that Win9x has a <a href="http://support.microsoft.com/support/kb/articles/q177/3/46.asp">bug</a> where<code>select()</code> can fail to block on a nonblocking socket. Itwill signal one of the sockets, which will cause your program to call<code>recv()</code> or <code>send()</code> or similar. That function willreturn <code>WSAEWOULDBLOCK</code>, which can be quite a surprise. So,a program using <code>select()</code> under Win9x has to be able to dealwith this error at any time.</p><a name="csocket"></a><h5>2.9 - What can you tell me about MFC's CSocket and CAsyncSocket?</h5><p>CAsyncSocket is a not-particularly-fancy asynchronous socketswrapper. I guess it makes using the asynch Winsock API slightly easier,but I personally prefer smarter wrappers that offer features likebuffering. (The same commentary applies to OWL's TSocket class. I haveno idea what VCL's socket library looks like, so I can't comment onit.) I suggest that if you want to use a Winsock wrapper, try some ofthe offerings linked on the <a href="resources/libraries.html">Libraries</a>page. I personally use my own Endpoint library, which is freely available,is much smarter than both OWL or MFCs offerings, and is compatible witheither class library. See the Libraries page for details.</p><p>As for CSocket, all I can say is <b>ick</b>. No, that's not true<img src="./bitmaps/waist-dot.gif" alt="-" width=7 height=6 hspace=2> I can say much more, but I'll restrain myself. CSocket is asubclass of CAsyncSocket that "fakes" blocking I/O using asynchronoussockets by running a small message pump every time it gets a<code>WSAEWOULDBLOCK</code> error. This is technically cute, but itcan cause reentrancy side effects. (While CSocket is "blocking", it'spumping messages, which allows a window message to trigger anothercall to the blocking CSocket object. The full list of similar and relatedproblems is left as an exercise to the reader.) Plus, various versions ofCSocket are known to have problems when used in nontrivial situations(e.g. several CSockets, each in its own thread). The most damningcriticism of CSocket, though, is that true blocking sockets are easy tocome by: the Winsock API is dead easy to program to when using blockingsockets. CSocket just isn't that much of a help to justify itself.</p><a name="localhost"></a><h5>2.10 - How can I test my Winsock application without setting up a network?</h5>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -