Library tutorials & articles
WinSock Control
By James Crowley, published on 14 Jul 2001
Introduction
The WinSock control allows you to communicate across PC's using the TCP or UDP protocol. It can also be used to contact servers across the internet
|
Related articles
Related discussion
-
VB6 Runtime error 381 subsript out of range Error
by Uncle (2 replies)
-
passing and reading parameters from using Shell
by jigartoliya (0 replies)
-
Convert C++ code to VB6
by mawcot (4 replies)
-
Help to Call ASP function from onclick event in HTML to pass an array
by vka (0 replies)
-
listbox scrollbar
by Dennijr (10 replies)
Related podcasts
-
Scott Guthrie
Scott catches up with Scott Guthrie in an interview covering Ajax, Asp 2.0, extender controls, CSS adapters and more.
Make sure that you have a reference to the winsock ocx, and a winsock control in the project and verify that its called tcpClient (you can prob add a line like Dim tcpClient as New mswinsck to load the control at runtime but my vb is a bit rusty so i dont know if that line is 100% correct sorry)
Hello, I was reading the "WinSock Control - Creating a Server" article
I followed it exactly the way it was done on the page.
I get the following error when testing my app though...
Run-time error '424':
Object required
When I click debug, this is the string that i get the error on:
Private Sub Form_Load()
tcpClient.RemotePort = 100 /////////*error line*//////////////
'// Get our Server Name, and set the form's caption
Caption = "prayog " & tcpClient.LocalHostName
End Sub
any ideas ,plz reply
akumar, you don't simply copy the EXE file on to other system. Use Package and Deployment wizard to make setup file so that it includes the winsock.ocx and other neccessary files. So that where ever you install your program will work. - Ramesh
you would either have to relay the message via the server -
ie client sends message >>>>> server >>>> server forwards to other client
or you would have to establish a connection between the 2 clients - either way you would probably have to relay some information to the other client(ie connection details) via the server
the 1st option would be fine if you're sending small amounts of information - ie text for a im program, but the 2nd option would probably be a lot more efficient and reliable for sending large files as it skips a hop.
the 2nd option could get complicated - in the case of computers being behind router/firewalls and setting up port forwarding on each client in order to accept a connections - maybe someone knows a way around this???
wheras the 1st option only requires a port opened/forwarded on the router/firewall that connects the server to the internet
Anyways hopefully that gives you a few ideas - also the 2nd option is probably better if you intend to use the program over lan only or if you need to transfer large amounts of data.
When I should use WinSock control method Bind() ?
Can I in some way to listen on port 80 when for example Apache server is listening on this port without Winsock control to return error "Address in Use"
thanks for this tutoril, it's really helped, but can anyone please explain to me how to enable to two clients to be able to communicate with each other, because so far all i can do is communicate between the client and server. Would each window have to be a server for this to work? thanks in advance.
The first bug is relatively minor and deals with dynamically loading and unloading the control. A memory leak is incurred when unloading a previously loaded control. This is why we don't load and unload the controls as clients connect and disconnect in our server example. Once the control is loaded in memory, we leave it for possible use by other clients.
The second bug involves closing a socket connection before all data queued is sent on the wire. In some cases, calling the Close method after the SendData event (when Close is processed before SendData) causes data to be lost, at least from the receiver's point of view. You can get around this problem by catching the SendComplete event (which is triggered when SendData has finished putting the data on the wire). Alternatively, you could arrange the send/receive transactions so that the receiver issues the Close command first, when it has received all the data expected. This would then trigger the Close event on the sender, which would then signal that all the data sent has been received, and that it's now OK to shut down the connection completely.
The last and most severe bug is the dropping of data when a large buffer is submitted for transfer. If a large enough block of data is queued up for network transmission, the control's internal buffers get messed up and some data is dropped. Unfortunately, there is no completely perfect workaround for this problem. The best method is to submit data in chunks less than 1000 bytes. Once a buffer is submitted, wait for the SendComplete event to fire before submitting the next buffer. This is a pain, but it's still the best way to make the control as reliable as possible.
From my experience, you can overflow the buffer on the receiving machine even if you trap the SendComplete event. I believe the event fires after the send buffer is cleared, but if you immediately send more data then there is no guarantee that the receiving machine will have taken that data and used it before reading the next buffer. I still lose (large) chunks of data on slow aircard connections. I may follow up in the future as I Endeavour to complete my mission-critical application. If sending more data than the buffer can handle, I suggest handshaking the messages. Use a stop character to end each message sent. When this stop character is received, send a message back to the sender saying, “yes, I received a message.”
Hello everybody!!!.
Can i use winsock conection with a dial-up. I mean i want to call to a Computera A via modem Computer B answer the call, the whole process handle with winsock. Can i do this??
Please i need this information.........
If i connot do it this way, how can i do it??
Thanks.
When i try to run the Startup form, i having some error message. The error mesage show like this:
- As i type the PC Name of the Server in the Client Form, it comes with Run Time Error '40020': Invalid Operation at Current State
- If i type a message in the Server Form and try to send, a Window Propmt comes with a statement like "You must connected to the client first.
I really need some help for the problem above.
I think, You must have real IP address of the server process. if you communicate with the server application using client. and you are using proxy then the server application should be executed on the machine which has real IP.
Your client application need not be have real IP it will directly connected with the server appliation and once the connection is established by the client then u are free to communicate.
I believe that that code shuts down a remote computer
Hey
To all of u.
I connect to internet using proxies so what is the process to connect my vb applications using winsock to connect to internet. Many toturials on winsock describing the client server app. I want to know how i connect to internet using winsock in my app's + how to handle proxies in winsock control + my LAN administrator server also need authentication how this can be done using winsock to automatically log userid and password.
All Comments and Resources gives high regards.
Private Sub Form_Load()
TxtPort.Text = Winsock1.LocalPort
If TxtPort.Text = "0" Then
TxtPort.Text = "10101"
End If
Winsock1.LocalPort = TxtPort.Text
txtIP.Text = Winsock1.LocalIP
Winsock1.Listen
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim strCommand As String
Winsock1.GetData strCommand
If txtCommand.Text = "SHUT DOWN" Then
AdjustToken
ExitWindowsEx (EWX_SHUTDOWN Or EWX_FORCE Or EWX_REBOOT), &HFFFF
End If
Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
Winsock1.Close
Winsock1.Accept requestID
End Sub
Private Sub cmdShutdown_Click()
Dim strCommand As String
txtCommand.Text = "SHUT DOWN"
strCommand = txtCommand.Text
wnsCommand.SendData strCommand
DoEvents
End Sub
Private Sub cmdConnect_Click()
wnsCommand.RemoteHost = txtIP.Text
wnsCommand.RemotePort = TxtPort.Text
wnsCommand.Connect
cmdConnect.Visible = False
cmdDisconnect.Visible = True
End Sub
Private Sub cmdDisconnect_Click()
wnsCommand.Close
cmdConnect.Visible = True
cmdDisconnect.Visible = False
End Sub
Module
Option Explicit
Public Type LUID
UsedPart As Long
IgnoredForNowHigh32BitPart As Long
End Type
Public Type TOKEN_PRIVILEGES
PrivilegeCount As Long
TheLuid As LUID
Attributes As Long
End Type
Const EWX_SHUTDOWN As Long = 1
Const EWX_FORCE As Long = 4
Const EWX_REBOOT = 2
End Sub
Declare Function GetCurrentProcess Lib "kernel32" () As Long
Declare Function OpenProcessToken Lib "advapi32" ( _
ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long
Public Declare Function LookupPrivilegeValue Lib "advapi32" _
Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, _
ByVal lpName As String, lpLuid As LUID) As Long
Public Declare Function AdjustTokenPrivileges Lib "advapi32" ( _
ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, _
NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, _
PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Public Sub AdjustToken()
Const TOKEN_ADJUST_PRIVILEGES = &H20
Const TOKEN_QUERY = &H8
Const SE_PRIVILEGE_ENABLED = &H2
Dim hdlProcessHandle As Long
Dim hdlTokenHandle As Long
Dim tmpLuid As LUID
Dim tkp As TOKEN_PRIVILEGES
Dim tkpNewButIgnored As TOKEN_PRIVILEGES
Dim lBufferNeeded As Long
hdlProcessHandle = GetCurrentProcess()
OpenProcessToken hdlProcessHandle, (TOKEN_ADJUST_PRIVILEGES Or _
TOKEN_QUERY), hdlTokenHandle
LookupPrivilegeValue "", "SeShutdownPrivilege", tmpLuid
tkp.PrivilegeCount = 1
tkp.TheLuid = tmpLuid
tkp.Attributes = SE_PRIVILEGE_ENABLED
AdjustTokenPrivileges hdlTokenHandle, False, tkp, _
Len(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded
End Sub
what is does is basically have a main winsock control that is listening on port x from the beginning (this can have index 0 and be created a design-time)
Winsock(0).Listen
and when there is a connection request:
If Index = 0 Then
Dim NewIndex As Integer
NewIndex = UBound(Winsock) + 1
Load Winsock(NewIndex)
Winsock(NewIndex).Accept requestID
End If
End Sub
and that's all the code. when there's an error, you want to display it and then close that winsock, or in the listening winsock case, you want to start listening again. you don't have to have the listening winsock as index 0 - it can have any name.
Sorry,
As I haven't programmed with VB a while, I am not able to help you. Hovewer, when putting all this code together that is posted here you should get it all right, like I did. I can also give theoretical information as I don't even remember the syntax of VB, and might 80% give wrong code. If you have decent knowledge of the structure of VB you should be able to do it.
Again, sorry... No offence
People
Like myself are only viewing this when someone has bumped the topic... me myself, id love to know how to get it working... but not if its gonna cause offence
And can't believe this either that after 2 years people are still ACTIVELY monitoring this topic. lmfao
Dan Forever said:
before you said the code above doesn't work, could you tell me how you fixed that or at least give me some tips / pointers?
How can anybody help you to get it working when that person him/herself didn't get it working?
hehe
WOW!
Look at the time of the original comment! Now I have returned, with a different nick (damn missing password generator!
) and still after years people are puzzled with it
Man, it was so long ago I even don't remember the solution. lol. Maybe a little... Well, here's your answer: do a google on how to use control arrays in VB. Just create a control array of sockets and when an incoming connection event is triggered, create a new socket in the array and let IT accept the connection, rather than letting the LISTENER to accept the connection (making it abandon it's listening state and switch to connected state)
Call me a dufus but i cant get this working - I think im having trouble understanding the control array aspect of it
If someone could provide a VERY simple example in full... I would be very grateful
I would also appreciate the info on how to xfer files but that code is very... extensive
is there a simpler way or an explanation
I think if another program is using that port, your program will crash, or not get a reply. I suggest you open mIRC, then have your program connect on port 6667 (the port mIRC uses) and see what happens. If it crashes, you can use an error handler to make it try another port instead. If it just doesn't connect, have it try a few more ports before giving up. The program on the other end should be listening on all the ports that may be used, and when a connection is established stop listening on every port except the one it's connected on.
server and the client in the same computer and tree more clients in others
computers, by now the program works fine, but I do not if it is correct
to ask to the client for the port it is using to listen because I do not who to reserv
a port for my application program only. The only fixed port is the server
listen port. How can I do to be sure than another applications do not use
the same port my application is using. Me applications is a real time program to
get data from the factory process and to advise the factory operator about
problems in the process. It works well but the other day another programmer
was testend a application and it has using the same port than my application
and it stops with the "error port is in use".
Please, excuse my poor English
Hello, I was reading the "WinSock Control - Creating a Server" article
I followed it exactly the way it was done on the page.
I get the following error when testing my app though...
Run-time error '424':
Object required
When I click debug, this is the string that i get the error on:
Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
tcpServer.GetData strData
txtreceive.Text = strData
End Sub
on the txtreceive.Text = strData string I get the error.
Any ideas?
I know exactly what is wrong because I had the same problem. This article has a minor spelling mistake. In the first part of the server, when it tells you the names to name the controls, it says txtRecieve, with an 'ie'. However, in the code, it uses txtReceive. Change the control's name to 'ei' instead of 'ie', and it will work like a charm.
I only speak a lite bit of english
I would like to now the name of the file in Windows to define a new
LocalPort (UDP port)
thanks Javier
Yes you're right... but in my case... when my VB.NET application have to connect to the vbce application which is working with winsock control, i think i have to use winsock control.
And actually, i can connect, and i can send data without any problems from VB.NET to VB(winsock). But the problem is when i'm trying use:
Private Sub TcpServerPDA1DataArrival(ByVal sender As Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEventsDataArrivalEvent) Handles TcpServerPDA1.DataArrival
dim string
tcpserver.getdata(string)
msgbox(string)
end sub
is not working... is not even showing the msgbox! Is just leaving procedure.
So can anybody tell me... how to read packets in VB.NET which are sended from VB (winsock control)??
'Heres the download module I'm using for my gnutella client
'You should be able to make it out from this.
' I can post the upload module if you wish
'Basic download routines like receiving data, storing etc
'Dim DLBytePosition&(0 To 32767)'can store a byte position for every
'winsock thread ;)
'for later use
'ToDo: Set LocalFile$, filter / create HTTP header
Public Function InitDownload%(WinsockIndex%, LocalFile$, Size)
'this function returns the file number of the opened file
'or -1 if the initialization failed.
'(e.g. invalid filename, file already open, disk full,etc)
On Local Error GoTo InitDownloadError
FFILE% = FreeFile 'find a new file number for open
Open LocalFile$ For Binary As #FFILE%
'this command openes the file and holds it open until
'close #FFILE% or until programm closed
'Now the file is opened and ready for our dataArrivals
InitDownload% = FFILE%
'Doing some additional work
File = Mid(LocalFile, InStrRev(LocalFile, "\") + 1, Len(LocalFile))
If downloadmessage(WinsockIndex%).fileindex = 0 Then
downloadmessage(WinsockIndex%).fileindex = addtodownloads(File, "Downloading", 0, Size, 0)
End If
Exit Function
InitDownloadError: InitDownload% = -1
End Function
Public Sub RebuildBroken()
Set objTS = objFS.OpenTextFile(App.Path & "/broken.net", ForReading)
While Not objTS.AtEndOfStream
Temp = objTS.ReadLine
Temp = Split(Temp, "|")
downloadmessage(Int(Temp(7))).fileindex = addtodownloads(Temp(0), "Connecting", Temp(1), Temp(2), "0")
Call OpenFileTransfer(Int(Temp(6)), CStr(Temp(0)), Temp(3), Temp(4), Temp(1), Temp(2), Int(Temp(7)))
Wend
End Sub
Public Function StoreData&(Filenum%, DataString$)
'This function is for storing incoming Data into a
'download file
'it returns -1 when storage failed, or the new file size(bytes)
'when success.
On Local Error GoTo StoreDataError
Seek #Filenum%, LOF(Filenum%) + 1 'point to next byte(for writing)
Put #Filenum%, , DataString$ 'write data
StoreData& = LOF(Filenum%) 'new file length
'MsgBox StoreData
Exit Function
StoreDataError: StoreData& = -1
End Function
Public Function CloseDownload%(Filenum%)
'This function closes the file, socket,remove from listbox etc (TODO)
On Local Error GoTo CloseDownloadError
Close #Filenum%
downloadmessage(Index).filerunning = False
Exit Function
CloseDownloadError: CloseDownload% = -1
End Function
'Coded by Guo Xu
'Opening FileTransfer. Opens new socket and sends the request after connect
'Creates a new array using the type strdownloaddata to store the needed
'information.
Public Sub OpenFileTransfer(FileIndex As Integer, FileName As String, ip, port, StartRange, Filesize, Optional DLIndex As Integer)
packet = "GET /get/" & FileIndex & "/" & FileName & " HTTP/1.1" & vbCrLf
packet = packet & "User-Agent: " & Version & vbCrLf
packet = packet & "Host: " & ip & ":" & port & vbCrLf
packet = packet & "Connection: Keep-Alive" & vbCrLf
If StartRange = 0 Then
packet = packet & "Range: bytes=0-" & vbCrLf & vbCrLf
Else
packet = packet & "Range: bytes=" & StartRange & "-" & vbCrLf & vbCrLf
End If
'MsgBox packet
For i = 1 To frmMain.DownloadSock.UBound
If StartRange = 0 Then
If frmMain.DownloadSock(i).state = 0 Then
'MsgBox i
If downloadmessage(i).filenumber = 0 Then
frmMain.DownloadSock(i).Connect ip, port
downloadmessage(i).filemessage = packet
downloadmessage(i).filename = FileName
downloadmessage(i).filesize = Filesize
downloadmessage(i).fileremoteindex = FileIndex
downloadmessage(i).fileip = ip
downloadmessage(i).fileport = port
Call Msg("Requesting file. On DLSocket " & i)
Exit For
End If
End If
Else
If frmMain.DownloadSock(DLIndex).state = 0 Then
If DLIndex <> 0 Then
frmMain.DownloadSock(DLIndex).Connect ip, port
downloadmessage(DLIndex).filecurrentsize = StartRange
downloadmessage(DLIndex).filemessage = packet
downloadmessage(DLIndex).filename = FileName
downloadmessage(DLIndex).filesize = Filesize
downloadmessage(DLIndex).filerunning = True
downloadmessage(DLIndex).fileremoteindex = FileIndex
downloadmessage(DLIndex).fileip = ip
downloadmessage(DLIndex).file_port = port
Call Msg("Requesting file. On DLSocket " & DLIndex)
Exit For
End If
End If
End If
Next
&nb
'Heres the download module I'm using for my gnutella client
'You should be able to get the idea from this - if you wish I can post the upload module
'Basic download routines like receiving data, storing etc
'Dim DLBytePosition&(0 To 32767)'can store a byte position for every
'winsock thread ;)
'for later use
'ToDo: Set LocalFile$, filter / create HTTP header
Public Function InitDownload%(WinsockIndex%, LocalFile$, Size)
'this function returns the file number of the opened file
'or -1 if the initialization failed.
'(e.g. invalid filename, file already open, disk full,etc)
On Local Error GoTo InitDownloadError
FFILE% = FreeFile 'find a new file number for open
Open LocalFile$ For Binary As #FFILE%
'this command openes the file and holds it open until
'close #FFILE% or until programm closed
'Now the file is opened and ready for our dataArrivals
InitDownload% = FFILE%
'Doing some additional work
File = Mid(LocalFile, InStrRev(LocalFile, "\") + 1, Len(LocalFile))
If downloadmessage(WinsockIndex%).fileindex = 0 Then
downloadmessage(WinsockIndex%).fileindex = addtodownloads(File, "Downloading", 0, Size, 0)
End If
Exit Function
InitDownloadError: InitDownload% = -1
End Function
Public Sub RebuildBroken()
Set objTS = objFS.OpenTextFile(App.Path & "/broken.net", ForReading)
While Not objTS.AtEndOfStream
Temp = objTS.ReadLine
Temp = Split(Temp, "|")
downloadmessage(Int(Temp(7))).fileindex = addtodownloads(Temp(0), "Connecting", Temp(1), Temp(2), "0")
Call OpenFileTransfer(Int(Temp(6)), CStr(Temp(0)), Temp(3), Temp(4), Temp(1), Temp(2), Int(Temp(7)))
Wend
End Sub
Public Function StoreData&(Filenum%, DataString$)
'This function is for storing incoming Data into a
'download file
'it returns -1 when storage failed, or the new file size(bytes)
'when success.
On Local Error GoTo StoreDataError
Seek #Filenum%, LOF(Filenum%) + 1 'point to next byte(for writing)
Put #Filenum%, , DataString$ 'write data
StoreData& = LOF(Filenum%) 'new file length
'MsgBox StoreData
Exit Function
StoreDataError: StoreData& = -1
End Function
Public Function CloseDownload%(Filenum%)
'This function closes the file, socket,remove from listbox etc (TODO)
On Local Error GoTo CloseDownloadError
Close #Filenum%
downloadmessage(Index).filerunning = False
Exit Function
CloseDownloadError: CloseDownload% = -1
End Function
'Coded by Guo Xu
'Opening FileTransfer. Opens new socket and sends the request after connect
'Creates a new array using the type strdownloaddata to store the needed
'information.
Public Sub OpenFileTransfer(FileIndex As Integer, FileName As String, ip, port, StartRange, Filesize, Optional DLIndex As Integer)
packet = "GET /get/" & FileIndex & "/" & FileName & " HTTP/1.1" & vbCrLf
packet = packet & "User-Agent: " & Version & vbCrLf
packet = packet & "Host: " & ip & ":" & port & vbCrLf
packet = packet & "Connection: Keep-Alive" & vbCrLf
If StartRange = 0 Then
packet = packet & "Range: bytes=0-" & vbCrLf & vbCrLf
Else
packet = packet & "Range: bytes=" & StartRange & "-" & vbCrLf & vbCrLf
End If
'MsgBox packet
For i = 1 To frmMain.DownloadSock.UBound
If StartRange = 0 Then
If frmMain.DownloadSock(i).state = 0 Then
'MsgBox i
If downloadmessage(i).filenumber = 0 Then
frmMain.DownloadSock(i).Connect ip, port
downloadmessage(i).filemessage = packet
downloadmessage(i).filename = FileName
downloadmessage(i).filesize = Filesize
downloadmessage(i).fileremoteindex = FileIndex
downloadmessage(i).fileip = ip
downloadmessage(i).fileport = port
Call Msg("Requesting file. On DLSocket " & i)
Exit For
End If
End If
Else
If frmMain.DownloadSock(DLIndex).state = 0 Then
If DLIndex <> 0 Then
frmMain.DownloadSock(DLIndex).Connect ip, port
downloadmessage(DLIndex).filecurrentsize = StartRange
downloadmessage(DLIndex).filemessage = packet
downloadmessage(DLIndex).filename = FileName
downloadmessage(DLIndex).filesize = Filesize
downloadmessage(DLIndex).filerunning = True
downloadmessage(DLIndex).fileremoteindex = FileIndex
downloadmessage(DLIndex).fileip = ip
downloadmessage(DLIndex).file_port = port
Call Msg("Requesting file. On DLSocket " & DLIndex)
Exit For
End If
End If
End If
Next
&n
Hello, I was reading the "WinSock Control - Creating a Server" article
I followed it exactly the way it was done on the page.
I get the following error when testing my app though...
Run-time error '424':
Object required
When I click debug, this is the string that i get the error on:
Private Sub tcpServer_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
tcpServer.GetData strData
txtreceive.Text = strData
End Sub
on the txtreceive.Text = strData string I get the error.
Any ideas?
How do I get this to work with a RichTextBox, I've tried, but nothing gets entered into the recieve box
you would probably want to create a sub that enables and disables all
buttons on your form something like:
Private Sub ButtonState(Msg As Boolean)
If Msg Then
Disable/Enable your command Buttons
Else
Enable/Disable you command Buttons
End If
End Sub
in your timer
If Winsock1.State <> SckConnected Then ' if not connected
Call ButtonState(False) ' Disable Buttons
Winsock1.Connect "host", Port ' Reconect
Do While Winsock1.State <> SckConnected 'loop while connection is commencing
DoEvents ' give control back to user
Loop
' when you get here your winsock has made a new connection
Call Buttonstate(True) ' Enable Buttons
End If
Lee, VbExplorer
VB.NET has made significant changes to the way these things work, and basically you shouldn't use the WinSock control in .net.... take a look at the System.Net and System.Net.Sockets namespaces instead.
I know how to connect and all of that, but I need to know how to transfer files. All the places I looked on the web want me to convert to binary first, which makes sense, but im not exactly sure how
can someone please give me some feedback on this, thanks
I had the same problem as you dude. I can do all the chats and multi-connects in VB6, but when I try and do it in VB.net, it wont work at all. It has all these errors and stuff, and it wont let me type what I want. I will always change it by adding or taking away brackets and quotations. I have no idea whats wrong with it, or if you just have to learn new code to get around it
This is a great site I learned all the basics about the Winsock Conrtol, it doesnt skip out on anything. When you are doing good with the basics, it has some more complicated stuff like mulit-connects and stuff
http://www.winsockvb.com
Take out the If..Then Statement. The index might change, so it might not count, try this
'This goes in the Winsock_ConnectionRequest Part
chatConnect = chatConnect + 1
load winsock(chatConnect)
Winsock(chatConnect).Accept RequestId
Hope THis works!
All you have to do is make a label that tells you if you are connected or not. on the "winsock_connect" part, put it so that when it does connect, the caption says "connected". Then you can use a Timer(set for 500 or something) and an If..Then Statement like this
'This goes in the Winsock1_Connect Part
Label1.Caption = "Connected"
' This goes in the Timer Control
If Label1.Caption = "Connected" Then
Winsock1.Connect "host-goes-here", port#here
End If
' End Code
I have made simalar program that did this, I didnt want to have to connect them all the time, so I made it do it automaticly, hope this is some help!
hi,
What should i do if in a client server model , client is under proxy...how will client connect to server
Anwar
ok i think u dled vb (just vb) and you didnt dled MVS (microsoft visual studios).
What version are you all using for this program? I am using VB.NET Professional, and I don't think everything is the same. Let me know... Thanks.
can any one teach me how to make my client form Automaticly connect
to the server if ever it was disconnected...
In short, you keep creating multiple instances of your Winsock control using the "Load" function as more connection requests come in.
As for not finding the Winsock control in your list of modules, try going to the Project menu -> Components and then scrolling down to "Microsoft Winsock Control 6.0 (SP5)". Check the checkbox to the left of that entry, and the Winsock control should show up in your controls palette on the left hand side of your screen (the Winsock control icon looks like two computers with a small red arrow curving between them).
Hope that was helpful!
Bill
billin@jadeforest.com
Private Sub Form_Load()
Dim Outputstring As String
Outputstring = "some text"
' set receivig side
Winsock1.Bind 8526 ' portnumber < 65536
' set sending side
' Winsock2.RemoteHost = "127.0.0.1" ' remote side ip in form "x.x.x.x"
Winsock2.RemoteHost = "localhost"
Winsock2.LocalPort = 65535 ' portnumber < 65536
Winsock2.RemotePort = 8526 ' we send data to winsock1 listening port
Winsock2.SendData (Outputstring)
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim Inputstring As String
Winsock1.GetData Inputstring
Debug.Print Inputstring
End Sub
I use winsock to transfer some files beetwin 2 PCs. my program work fine, but the transfer speed is slow.
Is there something to set the transfer speed?
thx.
Cláudio
The tutorial is great for beginners! But... you forgotten one important thing: how to connect more than one client to a server! This is really important! It is really simple, but vital!
I think it would help quite much if you told us where it went wrong and what the compiler has to say about it.
This tutorial really is great.
As for that matter of fact, it's probably the very best tutorial about winsock programming I've ever read.
However, it only concentrates on TCP connections.
Does anyone have any idea where I would find a tutorial about UDP connections, using winsock?
Sussed it, it was not a dumb instal program, it was a dumb me that did not select ActiveX components when i installed VB!!!!!
Dumb dumb dumb, i know!!
Thanks anyway
wierd!
Prolly some dumm ass program has uninstalled it? Try re-running SP5 setup to see if it will re-install it(may not) otherwise download it from the web and register it.
Are you sure u cant see it in the list?
Having trouble with any winsock stuff,
can anyone help
I cannot find the winsock control, I am running VB6 with SP5 on XP and i have tried to find it in the list of controls but it is not there!!
Anyone got any ideas??
thanks guys & girls!!
I have follow your step. but it still cannot work.
I try to link the page but nothing inside
lol@james! Yeah right!
there is a basic example @ http://www.developerfusion.com/show/193/
there is a basic example @ http://www.developerfusion.com/show/193/
I never made the claim that it was scalable
... it's only supposed to be an introduction to the control. Since when does VB support multithreading anyway? (and since when was VB/the winsock control scalable...??)
before you said the code above doesn't work, could you tell me how you fixed that or at least give me some tips / pointers?
Private Sub wnskChat_ConnectionRequest(Index As Integer, ByVal requestID As Long)
I get a wierd error about not recognising that, but it works without the index as int.
would wnskChat_DataArrival(blah blah) work for every wnskChat in a control array?
u wanna see the code, nah sorry i dont give out code, and especially in beta's. far too buggy, if u wanna see the exe at the moment then i attached a zip file, the exe and pic must be in the same directory, any probs let me know.
chad
chad
I'm currently trying to get to network a game I made with a friend that works in 'hotseat' mode, but recieving info from clients seems to present a problem. mainly because changing anything at all in the datarecieved sub means VB6 says "I don't recognise this" - adding index as integer, and you can't stick the index number in after the name cos it confuses it with the variables that would be in the backets at the end of a sub
How to send file for example mp3, pic, etc by using winchock?
It might be worth taking a look at the SocketWrench control...
NetGert: there are numerous C++ compilers available... Take a look at some of the websites listed at http://www.developerfusion.com/c/
Do they use C++? I've heard a lot of good about that. If anyone works with C++, please give me the URL where I can download that.
LOL
After searching the internet for hours I've finally found something that works. Being a complete beginner at winsock vb, this tutorial is a superb starting point. Thank you.
But what are they then using? Delphi?
How to send file for example mp3, pic, etc by using winchock
hello, im starting to experiment with vb see what i can do, has anyone done an example of a winsock chat that can allow more than one client? when i tried the code i still got the same errors. If anyone can help me out my email addy is chad_leverington@hotmail.com
thanks in advance
chad
NetGert: there is no mystery. The difference is they don't use Visual Basic to write their programs
You need to set up a control Array. The first Array (0) should be the listening Socket. On its Connection Request Have it load a new Object. Since the connection was already accepted you don't need to set the port so assign it to 0.The code looks like this:
Private Sub wnskChat_ConnectionRequest(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
intMax = intMax + 1
Load wnskChat(intMax)
wnskChat(intMax).LocalPort = 0
wnskChat(intMax).Accept requestID
End If
End Sub
Good Luck!
How to connect to multiple clients? Like Chats do? If I want to connect another client to server, it won't connect, it gives an error. What should I do?
How about some REAL multithreaded code that would actually stand up to a real world scenario...
Hello,
I am using a phone line and a modem to connect to internet like my friends.
We have different ISPs, is it possible to write a chat program with WinSock in VB? If yes when will it work and how? I mean will chat programs which are written in VB with WinSock work when Server and Clients computers are connected to different ISPs With modem? Or something else is needed?
Please reply to: "m_jahedbozorgan@hotmail.com"
Best Regards
M. Jahedbozorgan
There is, but you have to send the data, not the file itself.
Do something like this:
Dim iLines, iLine As Integer
Dim sLine As String
'Read how many lines are in the file
'
Winsock1.SenData "LINES " & iLines
While Not EOF(1)
'Read a line
'
'Send it
Winsock1.SendData "LINE " & iLine & " "sLine
iLine = iLine + 1
Wend
I think you got the idea by now.
I ment the same thing
mIRC and other IRC chat clints are somehow able to connect to one port, without getting an error. The same do the servers, they can hold many clients on 1 port. I've checked all ports, they don't direct and don't use control arrays. HOW???.
The mystery will still remain...
I think...
Can i use a port for 2 clients at the same time?!?!?
Case no what i can do!?
Is there a way to modify this to send text files?
You need to create a Control array of WinSock controls... set the first winsock controls index property to 0. Then, you can create additional connections by doing
Load WinSockControl (1) 'next winsock control
'connect, or whatever
Load WinSockControl (2) 'next winsock control
How to connect to multiple clients? Like Chats do? If I want to connect another client to server, it won't connect, it gives an error. What should I do?
This thread is for discussions of WinSock Control.