Using the Winsock control to realize network point-to-point communication

Source: Internet
Author: User
Tags empty
Control | The ladder of network network second words:
Using the Winsock control to realize network point-to-point communication
Blog appears in Csdn, also blog will not blog also. You're going to ask why? Whether you have this question mark in mind, but in my heart this is a period! And you're going to ask why? Well, whether you ask or not. I have decided to answer now. But the cause and the consequences of that kind of long-winded, please forgive me to list. I can only directly and indirectly explain, blog appears in Csdn, also blog will not blog also.
Using VB, wrote the network program, did not try to Winsock this control is really regrettable (except API Master). I think no friend has this regret ... Oh! Because, through the Winsock control, you can simplify and simplify the network communication. What is the extent of that? It could be within 10 lines of code (IDE generated with the outside)! Because that is only network communication, and communication, just send a message, the other side received, display. Can you forget it? To see:

First, the window loads the process we write on:
' Set the first Winsock control into the wait
Winsock1.localport = 5052
Winsock1.listen
' Again, connect the second Winsock control to the first
Winsock2.connect "127.0.0.1", 5052

OK, this is when the Winsock1 control's Connectionrequest event is triggered. We write on:
If winsock1.state <> sckclosed Then winsock1.close
Winsock1.accept RequestID ' Accept connection

That's it! It's simple. Again:
Winsock1.SendData Text1.Text ' to pass the text in Text1 to each other

Of course, you pass the data to Winsock2, and its dataarrival events are triggered.
Dim Strdat as String
Winsock2.getdata Strdat ' access to data
Text2.text = Strdat ' shows up in Text2

At this point, a use of Winsock control, the realization of the network communication program is completed! hahaha, are you feeling cheated? This idea, MSDN, has been sold in the early! Gates is really not a cover, unexpectedly early thought with MSDN break me to the land! Oh, no wonder he's richer than me!

Did I finish the job? No, what I'm going to do is "use the Winsock control to achieve network point-to-point communication." Communication is realized and is also one point to another point. However, in the common sense, point to point is not so explained. What's the solution? It's two-way communication! Oh, but gates is always richer than me. This idea has been sold out in MSDN again!

Impatient, aren't you? But to write a program, you can not be afraid of annoyance. If you decide to go this way, there are more annoying and more annoying waiting for you. Hey, annoying, can you see it? Haha ~! Since all the good ideas have been sold to gates, what else is there to say? Just like, Bill sells you an empty datasheet, but does not fill in the data. It's still an empty datasheet, not a datasheet! But Bill can not help you fill in the appropriate data for you, so you have to follow your existing data table, to the empty data table to fill in data, and then delete the source data table, it becomes a unique data table!

I see you are really impatient ... Are you hungry? Steam the mouse to eat the top for a while!
OK, now let me talk about an important program in point-to-point communication applications ... But this time, it's not going to be like that, listing a line of code, and then telling you where to add it, and then how ... Now I would like to "teach people to fish" policy, adhere to the "programming emphasis on the idea" approach, to the "from the very beginning", from "Understanding to understanding" philosophy of the point of view. Explain, through the Winsock control, transfer files on the network VB program is how to write!

As in the previous example, using the Winsock control to communicate, you have to separate the client from the server, namely: client, Server (c\s). But as you all know, this is only a scene that must be staged using the TCP protocol. And in UDP, and there is no clear c\s separate! But this concept is going to blur. I will explain it later on in the topic. Today our main character is TCP.
In the example above, does the step of gradual steps be realized? Okay, now let's look back.

The server listens on port 5052.
Client-side connection to the server 5052 port, is the server program listening to the port!
Because of a customer connection, the Winsock control on the server program triggers the Connectionrequest event (see MSDN).
The server accepts the connection, and the Winsock control of the client program triggers the Connect event to indicate the connection (example omitted).
After the connection, the server program sends data to the client program.
The data arrives at the customer end, the Winsock control triggers the guest end program's DataArrival event prompt, obtains the data, displays!
The whole process is so, obviously very simple, right? Oh! Then we get a flow table after that. will begin to fill in the blanks. Open the file we want to send read the data to the server to send. After receiving the data, then write back to the file! The process is just like this! Concrete realization, still have to think about. OK, now let's think about it from a user's point of view!

Two a Winsock how to connect I don't say, anyway gates are already richer than me! Then we have to pass the file, first let the user select a file bar. And then you start to preach! Good biography, slow down! How does the client know what type of file the server is going to send? Good! With this idea, we get the name of the file that the user selected when the user clicks on the server program to transfer the file to the button. Going to pass through? Still not, if we this program is chat + Pass file, it is not very confusing? Well, give this information a name! What do you mean, "send"? Good, is a very domineering name ~ everyone used QQ and so on the chat software files are known, QQ will first ask the receiver whether to receive XXXX.XXX documents! Let's imitate it, set the routing and file name to: "Send filename", such a format. Then use the Winsock SendData method to pass to each other.

Then go to the client write code:
OK, when we receive this order, we can draw from the first 4 words, the other party will pass the document over! There is nothing to write, just play a MsgBox out to say, the other party to pass xxxx.xxx to you, you are willing to receive it? OK, when the user determines the save path, then in such a path, create a file that is written in case the data is received. We now have to return a message to the server that, called: "Iliefly" Bar! Represents a confirmation receipt.

Back to the server that wrote the code:
Receive confirmation information, we began to read the file operation! Open the file and declare a byte array. Read all the open file data into this array. haha ~ is not it? Then pass it over and try it.

The client is starting to receive data:
Hey, crap, how come there's a data type error? It turns out that whenever data arrives at the client, the code we write in the DataArrival event is executed. I thought it was an order or a chat! No, you have to set a tag for it to be used as a record of when the data passed over is the data of the file. Declare a static Boolean variable with a static statement (see MSDN), when false is our command or chat content, and true is the file data! Change the last time in the client that wrote the source code, in the promised to receive, the Boolean variable set to true! Ah? The problem comes out again! Then I thought, when can I set the Boolean variable back to false? Well, there's still a problem! Eyes focused on the server ...

Then back to the server's Code edit box:
Is there any way to let the client know when it's going to pass? Send a command? No, there will be a command written to the file. Connection closed? Even more, I have to chat ... Well, if you let the client know the length of the file that passed, then can you determine when you are finished receiving it? Ha ha! Action, change the transfer file command is: "Send filename file length." Oh? Too many spaces, so that the other party explained quite troublesome, with InStr? No, what if there are spaces in the file name? No, it's wrong again ... Luckily, we have split (see MSDN). Well, that's going to have to separate the order with a special character! Just vbNullChar it (see MSDN)! Change the command to: ["Send" & vbNullChar & filename & vbnullchar & file length]. Pass it on to each other. (Note: FileLen function)

The client wants to modify the code:
Declare a dynamic string array and attach the return value of the Split function to it, haha! Subscript 0 is the command, subscript 1 is the filename, subscript 2 is the file length! It's cool. Save the length with a module field variable to calculate when to close it! (Note: Val function)

Continue to write our code on the client:
The Boolean variable is true and there is data arriving. Then get the data from it! Note the type of data you receive Oh, the opposite is not a string, we want to specify the type of "VBArray + Vbbyte" (see msnd about GetData), meaning that the byte array. Of course, we're going to define a byte array to receive. Dim ByteArray () as Byte. Well, the length you just saved is useful, total length-the number of bytes received = number of bytes remaining. When the number of bytes remaining is 0, is the receiver finished? Ha ha! No hurry, first to organize the idea: The data arrives, gets, saves to the byte array. Use the UBound function (see MSDN) to get the largest subscript for the byte array, but because the array subscript 0 also has data, but the file is not so calculate ah, so to calculate on the +1 count! Total length = total length-UBound (ByteArray) + 1 Hey, okay!

Run and try and find a 50-MB pass. Oh, suddenly, clang! "Not enough memory" Halo! What the hell, look at the process list again, wow! My program takes up about 60MB of RAM! Dizzy, what's going on? Is there a mistake? To reorganize the idea: Select files, send commands, when received return confirmation message, open file, read ... Read??? No, I read the whole file into memory, no wonder (in fact, this error will not happen because Windows has virtual memory!). But it is true, to read the entire file into memory and then send out, a bit to make the system difficult ah! To optimize the optimization.

Go back to the server code for optimization:
Can't read so much at a time, that ... Let's split up! One delivery: How about 8,192 bytes? Good! That's it. But not every file is a multiple of the number of bytes in 8192, how to do? Well, make a calculation. Before we got the length of the file to be passed? Since each other can calculate when to collect, then I can calculate when the pass! First, make sure that the length of the file to be transmitted is not greater than 8192. If so, we'll put the file length-8192. Then define a byte array with a subscript of 8191 (because the array subscript 0 also can save the data, so-1), using the Get method, read the open file data to populate the byte array. Then pass through ... Well? The other side seems to be closed, the client does not set the Boolean array back when the total length of the file is not reached. But how do we know when we can pass the next data? Um, ~sendcomplete Event--occurs when a send operation is completed. Okay, that's it! We're here. The file length is 0 o'clock as a condition for ending the transfer. If not 0, then look at the number of files that have not been transmitted, because the above calculation has-gone to the last transmitted bytes, the current file length variable is the number of bytes left, and then compare, whether it is larger than 8192. haha ~ not to define a byte array of such size, read the file, send out! Complete ~[msgbox "Transmission complete!", vbinformation, "⊙_⌒γ-Server" ...
But suddenly found that the original Sendcomplete event, after we send the file command sent out will also trigger. That's impossible, so we have to define a Boolean variable to determine when to pass the file ...

At this point, a Winsock control to transfer files VB program finished! Oh, you're not asleep, are you? But I'm going to fall asleep! Good sleepy, the last time to sleep only 3 hours! Now-_-#了 ... But to explain, the above mentioned 8192, not I casually put up. This will be explained in detail in the future!

Well, it's not over yet! As if I did not say why: "blog appears in Csdn, blog will not blog also" haha ~ actually this article Dongdong has made it very clear!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.