kvbWinsockLib Bla Bla Bla - Just Show Me The Code  
   
 
VB developers often complain about having to use the VB Winsock control because it requires the use of (cheesy) control arrays on a form. Many tolerate it because writing to lower level socket API's are a pain. The KillerVB WinsockLib is a one of a kind drop-in replacement for the Winsock Control that ships with Visual Studio (MSWINSCK.OCX), and doesn't need a form to be hosted on. Use it to build chat, ftp or mail clients, to name a few. In fact, I used it in the KillerVB SendMailLib to send email directly to an SMTP server.
 
Live! Chat Sample Application

I've created a nifty chat application that demonstrates how simple it is to use the WinsockLib. It also demonstrates the simplest form of client/server socket-based programming. I've even been known to take calls from time to time, and can be reached at killervb.com on port 6666 (please don't call with general programming questions, although I may welcome calls specifically related to content on this site).
 
 
Winsock Control Compatible
 
The KillerVB Winsock library was designed with one important requirement: compatibility with the Winsock Control. Well, it's close, it's really close. There are some subtle differences, however. I collected several popular Winsock applications available from several popular VB sites. Within minutes I was able to convert them to use the KillerVB WinsockLib by changing but a few lines of code. Each application behaved identical to the version that used the Winsock control. Here's all it took to get these applications functioning:
  1. Add reference to the KillerVB WinsockLib and remove the Winsock control (tip).
  2. Dimension a socket at the module level (using WithEvents) and instantiate it when needed. It should have the same name as the control had on the form.
  3. Rename references to the "Close" method and "Close" event to "CloseConnection". This is because Close is a reserved word in VB.
  4. Rename references to "MSWinsockLib" to "WinsockLib" if any.
  5. Recreate the Error event with new parameter definition. This corrects a minor design flaw of the control.
  6. For server-side applications, ensure that the socket is Accept'ed on a new socket instance, or ensure that the listening socket was not closed before Accept is called, which is done automatically by the library.

That's it! Refer to the SendMailLib project for a demonstration of how simple it is to use.

Mo Betta
 
There are several improvements over the Winsock control that you might like. First, there are early bound events via the IWinsockEvents interface. This interface allows your form or class to receive events with fast vtable-bound methods. This technique also allows you to receive centralized events from an array or collection of WinsockLib instances.

The calling interface sports several enhancements too. For instance, you can send or receive data as ANSI or Unicode text, as a byte array, or as a pointer to raw memory. You can also send data synchronously, waiting until a transfer completes before execution continues.

The code for this library also serves as a good lesson about overlapped I/O, as well as server-side queueing of incoming data, which is important for stream-based client/server development.
 
kvbWinsockLib Code View License   The Code
kvbWinsock.Vbp
kvbLiveChat.Vbp
 
 
 
Visitor CommentsPost Comment
Flyguille - None
Well, as professional programmer, I was looking for a replacement of mswinsck.ocx because it is very buggy (like buffers overflows losing data on UDP transmission, Nothing that a DoEvents after the sck.send can fix because the DoEvent only works if there is another VB appl running a winsck). So i copy this code, reedited, fixed the code with the corrections already mentioned in the reactions's msgs. But UDP seems not work. The instance is create, the port is binded but when must to receive data (because it is a server side) the function "Public Function WindowProc" is NOT TRIGGERED. Surelly i will be able to fix it, but it is a lot of work overall I dislike the syntaxis (tabulations) that makes it a bit harded to read nicely. Anybody knows how fix it already?
David
This code simply does not work. In CWinsock.Connect ErrorCode = ioctlsocket(m_hSocket, FIONBIO, 1&) returns an error code 100% of the time. This looks to prevent the connection from going through. CWinsock.SendData needs the aformentioned check for UDP protocall otherwise it returns an error. Also, m_hSocket is always 0 if trying to send data UDP.. so that raises an error too. Way, way too many error trapping routines that take the code all over the place. This makes it very difficult to step through and try and fix. Poorly commented with bad tabbing style doesn't help that cause either. Whitespace between lines is your friend. This would be a fantastic library, if it actually worked.
(anonymous)
I was getting a 40006 error. When connecting, it seems I was getting an FD_READ event before FD_CONNECT (where the socket transitioned from sckConnecting to sckConnected). I noticed that in the connect method, you are setting FD_READ as well as FD_CONNECT and FD_CLOSE. And then in the FD_READ handler masking the FD_CONNECT flag. I changed this as follows: in the connect method, only set the FD_CONNECT and FD_CLOSE. Then in the FD_CONNECT handler reset the event flags to FD_READ and FD_CLOSE. This seemed to fix my problem (at least so far.....). I woul dbe interested in your comments as to if this is appropriate or if there may be a better solution.
Alpha - noone
I just can´t compile it, can anyone send me the full winsocklib project to pablogarcia89@hotmail.com ? Thanks
andy
First of all, thanx for such a perfect code, showing perfect what to do to 'socket' :-) But theres on question left. I had to modifiy your class a little bit, adding the function to sent a message to a thread notifying him about the events. I dont know really if my problem exists in the 'normal way' (using a eventhandler) too but when the data arrival event is fired, sometimes it is fired more than 4 or 5 seconds again and again, showing the same size and blowing the cpu to 50 - 100 %. Do you have any ideas? The only thing i modified is to add a var which holds the thread id, added some consts to hold message ids for different events AND a call to postthreadmessage at the right place. Any ideas? Searching for it since more than 6 hours now. Yours, andy
Eric Black
I believe there used to be a feedback message about this, but it's gone now... I followed the normal steps for UDP transmission (set the remote host & port, and bind the local port). SendData causes error 40006 (sckBadState). It appears to require the socket to be connected even though there's no connection in UDP. I don't know if it matters, but I have 1 app sending to another app on the same (WinXP) PC, both using WinsockLib. The same code works with the standard Winsock control. Thanks.
Joe Sheble
By any chance, would you happen to have any samples on how to best make use of this library? Studying exisiting code has always been much more useful than reading the actual code itself.. thanx
Hit
I found the UDP problem in his source. One of the first checks he does in the SendData method is check to see if the socket is connected...and since UDP is by definition a connectionless protocol, a further check should be added before raising the error to be sure that the socket type is not UDP. To fix this, I edited the following line in C Winsock.cls: If Me.State <> sckConnected And Me.State <> sckListening Then ErrRaise sckBadState to this: If (Me.State <> sckConnected And Me.Protocol <> sckUDPProtocol) And Me.State <> sckListening Then ErrRaise sckBadState This will allow it to work if in UDP mode. BUT WAIT, there's more! Since he initializes his outgoing collection buffer in the connect method, which UDP sockets don't use, we'll have to add these lines of code under the line of code I modified above: If m_OutgoingData Is Nothing Then Set m_OutgoingData = New Collection End If This seems to work. I haven't had a chance to extensively test it yet.
flyguille
little post, because I not supplied my email addr. (looking for updates)
Matt
how can i use your winsocklib in UDP mode? it seems not to work i get error #40006
Mr. I
Just tried if your code had such problem and ... Chat program in server mode runs ok, but in client mode gives "Run time error 429: ActiveX component can't create object" aha, CHEATING? I don't have winsock.ocx (or such thing under any other name) Anyway, I can't get it to work so far.
Rene - CAP
I've tried this lib and for the thing I needed it for it seemed to work great. However, just like Jason Gouldie mentioned, on a connection request the local address is not resolved until the connection is accepted. I needed this to check for valid requests before accepting the connectionrequest. In the meantime I found a solution to this, but the .net framework does not let me post it here. If anyone needs it, you can e-mail me at rened@100@yahoo@com. Remove the excessive @ to get a hold of me. This way I may get a little bit less spam.
Leontti Ramos - RamoSoft de Mexico
I have been reviewing the code and Wow! it is awesome! it is a well done winsock API implementation. I really like it! Great Job!
Rejitha - semifi technologies
i tried your kvbsendmail but it is giving an error tat activex component can't create object. can u plz provide me the solution .i m greatful to u if i get this since i hav an application tat hav to send mail directly to smtp server. thank you...
Ken
Hi, The winsock library seems not work properly for UDP connection. I followed the normal steps for UDP transmission that firstly Bind the local port, set the remote host and remote port number, and then SendData. I was getting a 40006 error for the SendData operation. I notice that the socket state is set to "sckOpen" after the Bind funciton has been executed without error. And within the SendData function, the error sckBadState(40006 error) will be raised if "State<>sckConnected" and "State<>sckListening". Please advise how t solve this problem.
Brian
your winsock library is great, i much prefer it to the standard winsock .ocx. i do however have one question. i am writing an app that will act sort of like a proxy server between a client and a remote site. it will run on a client's machine and respond to requests to 127.0.0.1:port. so the connection is between the local client and my proxy, which is also local. anyway, when calling the .Accept method, it always throws an error because the API call doesnt return a socket. anyway, i think the remoteaddr and localaddr might be stepping on each other since they are actually the same machine and address (localhost). how do i implement something like this? any guidance would be greatly appreciated. thanks.
Mr. I
Ghmm ... Previous problem solved, indeed. But stuck on the next one: When I'm trying to connect it stucks infinitely in While m_DataSocket.State <> sckConnected DoEvents Wend loop (stucks in "connecting..." state). Any ideas?
Mr. I
My experience 1.1. Downloaded killervb 1.2. Hmm ... It seems that excel does not understand any VB classes syntax - Removed all ATTRIBUTE from it (since excel VBA haven't got such implemented and just marks as error any VERSION 1.0 CLASS, BEGIN or ATTRIBUTE strings in class modules) 1.3. Hmm ... now it gives this error in MWinSock class module: "Constants, fixed-length strings, arrays, user-defined types and Declare statements not allowed as Public members of object modules" ... Uh ... "Cannot define a Public user-defined type within an object module". Fixed. (Finaly moved the whole MWinSock module away from class modules) 1.4. Fixed some duplicate declarations inside my modules like CopyMemory (RtlMoveMemory) from Kernel32 etc 1.5. "App" object seems to be undefined in VBA. Used values: App.EXEfile, APP.path, App.hInstance etc. Here comes the problem ... How do I get current application Instance in VBA? After I'll solve this problem I'll continue posting about my adaptation of this sockets lib for Excel (it's just one of a 3 winsock wrappers I'v found, so far it isn't that bad as the first one)
Alpha - noone
I just can compile it, all the codes are full of errors. Can someone send me the full winsock project to pablogarcia89@hotmail.com ? Thanks
Jason Gouldie
I just downloaded your WinsockLib projects, and think I found a bug. After establishing a connection to a remote host (TCP), I use the local and remote port to authenticate my data before sending and after receiving. The localport property is consistently returning 0. Looking at the code, it appears that the m_LocalAddr object is not being updated (using the GetSockName API call) prior to the ntohs() call in the Property Get LocalPort. Please confirm this problem and perform any necessary corrections. Please contact me via email when the problem is resolved, or if you need further information. Thanks, Jason
Boney
Been searching day and night for 2 days (yes day and night literally) looking for a winsock replacement... This is something ive never seen although some similar to this are ALOT harder to convert.. PSC (planet source code) cant compare to the complete work you guys have! My program is standalone now! No dragalong winsocks anymore -Boney 'ur the best'
Oracy
I tried both MS Winsock and Winsocklib, but I got (almost) the same error when connecting to a NTP service. As it seems, Winsocklib connects OK to service, because when I jump statements like "If State Not Connected Or Listening Then Raise an Error", I can get the data. WSAConnect returns SOCKET_ERROR, so State is not updateed corrrectly to sckConnected. Any idea why?
Dimi DOSida
Will WinsockLib be able to show me my external IP address if the computer I am using is behind a router? if not is there a way to directly communicate with the router to find out my external IP address, without bouncing off to any website?
Antonio
How can I make to correct the error number 40006? antonio88m@fastwebnet.it Thank you.
Ben Nelson - Didasko Communications, LLC.
This looks like it could be a great library ... if I could get it to work consistently on every computer. On the dev machine (Win 2K Server) it generates a 'memory at 0x00000000 could not be read' error ... when I attempt to include the class in the project as source code. This method works just fine on Windows 2000 Professsional, though. If I drop the class and reference the DLL, it works great on the development box, but every other computer complains that it doesn't have the correct license to access this functionality. How do I get this code to work everywhere? Thanks, Ben
mahmoud - ms
mm
Katie
I cant get any of the codes so i can get flash on my computer
Antonio
great! You have solved all my problems! Thank
flyguille
my email by if anybody has the fix to the problem that I mentioned before is flyguille at arnet.com.ar
Christian
While I found it works great with TCP connections, I'm having the same problems others had, with UDP sockets: the sckBadState error is raised (40006). Are you still mantaining this library? I mean, the last update was on 04/10/2002, more than a year ago... I'd appreciate any help. Thanks.
(anonymous)
jh
Mitesh H. Budhabhatti
U've given a great code here.... I've a different problem. Plzz tell me how can i use this code in multithreaded ActiveX EXE. Thanks in advance
Stephen Kennedy
Great site, lovely code. One problem - your VB to HTML script isn't working properly, meaning a lot of editing is needed in the VB before it will compile. It would be real nice if you provided zips.
 
Copyright © 1999-2002 by Monte Hansen, All Rights Reserved Worldwide.