Introduction Our First Winsock Application

Introduction Our First Winsock Application

Introduction A few years ago, I was called in to a hectic call-centre – the head honcho had a problem. Ironically, it was communication. Even though they had phones coming out of their ears (boom, boom), the people in this company simply couldn't talk to each other. Half of his staff were constantly on the telephone. The other half were temporary employees that didn't know each other's names and moved chairs quicker than a bunch of seven-years olds at a birthday party. The problem? When one of the workers had a query on an account and needed to question the last person dealing with it – they didn't know where to start. Who was who? The solution came as a simple package I very originally christened Talk – essentially a more personalised version of ICQ or MSN Messenger. And it worked. When an individual started work at a desk, they logged in. When they finished, they logged out. Somewhere in the middle, users could send messages to each other, have a digital chat – even send files to and fro. But how did it all work? By using the Winsock control. And this brief guide will demonstrate how to use it yourself – starting with a quick run-through of the basics, through to tips on setting up a chat session – plus handy links on how to initiate file transfers. We'll even cover how you can play Big Brother – and remotely control computers. So without further ado, prepare to enter the wonderful world of Winsock... Our First Winsock Application We'll start our look at Winsock by creating a mini messaging application. It's not going to be all-out bells and whistles, but you'll be able to send a message from computer A to computer B – and it'll give you a feel for how the 'Winsock control' works. So let's get started: · Launch Visual Basic · Click 'Project', 'Components' · Check the 'Microsoft Winsock Control' · Hit OK · Draw out the Winsock control onto your Form Now, the Winsock control is the key to this article. It allows you to easily communicate over a network. · Add a Text Box to your Form, changing its Name to 'txtAddress' · Add another Text Box to your Form, changing its Name to 'txtMessage' The first Text Box will hold the 'address' of the computer you want to send your message to. And the second box will hold the actual message itself. This will be sent "through" the Winsock control we added just a few seconds ago. · Add a Command Button to your Form · Insert the following code behind your button: Winsock1.RemoteHost = txtAddress.Text Winsock1.RemotePort = 1000 Winsock1.Connect Do Until Winsock1.State = sckConnected DoEvents: DoEvents: DoEvents: DoEvents Loop Winsock1.SendData (txtMessage.Text) Winsock1.Close Let's take a few seconds out to explain this code: Winsock1.RemoteHost = txtAddress.Text Winsock1.RemotePort = 1000 These first two lines of code simply tell the Winsock control which computer it should 'connect' to. The RemoteHost can either be a computer name or IP address. Top Tip: An IP address is a series of four numbers separated by dots, such as 102.42.35.32. It's just a numeric address that uniquely identifies your computer. Everyone on your network will have a unique IP address – and every time you connect to the Internet, your machine is automatically assigned an IP address – and no-one else on the Net will have the same address as yourself. It's sort of like a real address – information sent to that address only gets to yourself, no-one else. To find out your IP address, click Start, Programs, MS DOS Prompt, type 'IPCONFIG' then press return That second line of code simply sets the 'RemotePort'. This can be pretty much any number – and you can imagine it as a frequency on a radio dial. Here, you're tuning into 1000 FM on the other computer – and preparing to broadcast. Winsock1.Connect Do Until Winsock1.State = sckConnected DoEvents: DoEvents: DoEvents: DoEvents Loop This chunk of code simply attempts to connect to the remote computer – and loops around until it has that connection. Top Tip: It's worth noting that if a connection isn't made because, say, the other computer has just crashed or cannot be found, this code will just continue looping round and round. When an error occurs in Winsock, the State property equals sckError (9) – so you may want to add a little code to handle that here. Winsock1.SendData (txtMessage.Text) And finally, this last piece of code sends your message across to that other computer. So, that's our message-sending program, the client, finished. Now let's build the other end – the receiving application... Tuning the Receiver If you've ever attempted to build a real-life radio receiver (I have... D'OH!) - you'll be pleased to know that programming one in Visual Basic is so much easier. Let's get on with it: · Launch another instance of Visual Basic · Add the Winsock control · Behind the Form_Load event, add this code: Winsock1.LocalPort = 1000 Winsock1.Listen This tells your Winsock control to listen in to 1000 FM for any incoming messages. Next, let's add a little code behind the Winsock control itself. There are two main events we'll be dealing with here, ConnectionRequest and DataArrival. Let's cover these now: · Add the following code behind the ConnectionRequest event of the Winsock control: If Winsock1.State <> sckClosed Then Winsock1.Close Winsock1.Accept requestID This code will run when our program receives a connection request, such as from our message-sending client attempting to do a Winsock1.Connect. Firstly, this code ensures the Winsock control is 'closed' – in other words, makes sure it isn't connected to another computer. Then it accepts the connection request and the two computers are magically 'linked'. · Add the following code behind the DataArrival event of the Winsock control: Dim strIncoming As String Winsock1.GetData strIncoming MsgBox strIncoming This event fires up when information is arriving – when someone does a 'Winsock1.SendData' - following a successful connection. The first line creates a variable to store the incoming information. The second line slots the incoming information into the variable via the GetData method. After this you can do what you want with the data – I chose to simply display it in a message box. Top Tip: After you've retrieved the data via the GetData method, it disappears from memory. If you want to look at it without having it vanish from memory, use the PeekData method. And that's it! You've created both a program to send a message (the client) and a program to receive a message (the server). Of course, you could merge them both together to both send and receive, but we'll cover that in a couple of minutes. For now, let's test our project: · Press F5 in each copy of Visual Basic to start each application · In your message sending application, fill in the two Text Boxes – the first should contain the computer name or IP address of the machine you are sending the message to, the second should contain your actual message Top Tip: If you're running both the sending and receiving program on the same computer, you can use the IP address 127.0.0.1 – this number simply refers to your computer. Another Top Tip: It's always more stable using an IP address to locate a computer, than a machine name. But how can you find out a users IP address? Do what ICQ does! When your users log on, check out the Winsock's LocalIP property, which contains the users unique IP address. Then register this with some central database. When someone wants to send a message, lookup the user, find their IP address, then send them a message. When they log off, remove their details from your database. That's how the biggies do it! · Press the Command Button in your message sending program · Flip back to your receiving program Do you see a box holding your message text? You should do! If so, congratulations – you've just sent your first message via the Winsock control. And even if you're experimenting with this on your one computer – remember, it can work anywhere. You could be sending messages right across the office, via your company network, or even right across the globe thanks to the Internet. Now, let's briefly review the major code snippets we've looked at here – in printable format! Winsock Code Let's briefly review the raw code for building a simple messaging program with the Winsock control. All of this code is based around what we have discovered already, with a few slight enhancements: To Open a Connection If Winsock1.State <> sckClosed Then Winsock1.Close Winsock1.RemotePort = 1008 Winsock1.RemoteHost = "127.0.0.1" Winsock1.Connect To Wait until Connected Do Until Winsock1.State = sckConnected DoEvents: DoEvents: DoEvents: DoEvents If Winsock1.State = sckError Then MsgBox "Problem connecting!" Exit Sub End If Loop To Listen Out for Communication Winsock1.LocalPort = 1008 Winsock1.Listen To Accept an Incoming Connection Request Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long) If Winsock1.State <> sckClosed Then Winsock1.Close Winsock1.Accept requestID End Sub To Send Data Winsock1.SendData ("Data Goes Here") To Receive Incoming Data Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) Dim strIncoming As String Winsock1.GetData strIncoming x = strIncoming End Sub Going All Bi-Directional So far, we've created a program that sends messages. And a program that receives messages. But the send program can't receive.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    10 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us