手把手指导VB.NET Socket编程

开发 后端
这里介绍一直以来很想学习VB.NET Socket编程方面的应用,比如怎样通过VB.NET Socket编程实现单片机与PC的TCP连接通信。

VB.NET经过长时间的发展,很多用户都很了解VB.NET Socket编程了,这里我发表一下个人理解,和大家讨论讨论。一直以来很想学习VB.NET Socket编程方面的应用,比如怎样通过VB.NET Socket编程实现单片机与PC的TCP连接通信。在单片机嵌入网卡芯片与PC进行连接通信,实现PC的web方式对单片机所控制的设备的状态管理,例如智能家居方面的应用。

下面通过例子来学习VB.NET Socket编程类的应用,下面的程序分别分服务器和客户端两部分:

ImportsSystem  
ImportsSystem.Net  
ImportsSystem.Net.Sockets  
ImportsSystem.Text  
ImportsSystem.Threading  
ImportsMicrosoft.VisualBasic  
 
'Stateobjectforreadingclientdataasynchronously  
 
PublicClassStateObject  
'Clientsocket.  
PublicworkSocketAsSocket=Nothing 
'Sizeofreceivebuffer.  
PublicConstBufferSizeAsInteger=1024 
'Receivebuffer.  
Publicbuffer(BufferSize)AsByte  
'Receiveddatastring.  
PublicsbAsNewStringBuilder  
EndClass'StateObject  
 
 
PublicClassAsynchronousSocketListener  
'Threadsignal.  
PublicSharedallDoneAsNewManualResetEvent(False)  
 
'Thisserverwaitsforaconnectionandthenusesasychronousoperationsto  
'accepttheconnection,getdatafromtheconnectedclient,  
'echothatdatabacktotheconnectedclient.  
'Itthendisconnectsfromtheclientandwaitsforanotherclient.  
PublicSharedSubMain()  
'Databufferforincomingdata.  
Dimbytes()AsByte=New[Byte](1023){}  
 
'Establishthelocalendpointforthesocket.  
DimipHostInfoAsIPHostEntry=Dns.Resolve(Dns.GetHostName())  
DimipAddressAsIPAddress=ipHostInfo.AddressList(0)  
DimlocalEndPointAsNewIPEndPoint(ipAddress,11000)  
 
'CreateaTCP/IPsocket.  
DimlistenerAsNewSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)  
 
'Bindthesockettothelocalendpointandlistenforincomingconnections.  
listener.Bind(localEndPoint)  
listener.Listen(100)  
 
WhileTrue  
'Settheeventtononsignaledstate.  
allDone.Reset()  
 
'Startanasynchronoussockettolistenforconnections.  
Console.WriteLine("Waitingforaconnection...")  
listener.BeginAccept(NewAsyncCallback(AddressOfAcceptCallback),listener)  
 
'Waituntilaconnectionismadeandprocessedbeforecontinuing.  
allDone.WaitOne()  
EndWhile  
EndSub'Main  
 
 
PublicSharedSubAcceptCallback(ByValarAsIAsyncResult)  
'Getthesocketthathandlestheclientrequest.  
DimlistenerAsSocket=CType(ar.AsyncState,Socket)  
'Endtheoperation.  
DimhandlerAsSocket=listener.EndAccept(ar)  
 
'Createthestateobjectfortheasyncreceive.  
DimstateAsNewStateObject  
state.workSocket=handler 
handler.BeginReceive(state.buffer,0,StateObject.
BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)  
EndSub'AcceptCallback       PublicSharedSubReadCallback(ByValarAsIAsyncResult)   DimcontentAsString=String.Empty     'Retrievethestateobjectandthehandlersocket   'fromtheasynchronousstateobject.   DimstateAsStateObject=CType(ar.AsyncState,StateObject)   DimhandlerAsSocket=state.workSocket     'Readdatafromtheclientsocket.   DimbytesReadAsInteger=handler.EndReceive(ar)     IfbytesRead>0Then   'Theremightbemoredata,sostorethedatareceivedsofar.   state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead))     'Checkforend-of-filetag.Ifitisnotthere,read   'moredata.   content=state.sb.ToString()   Ifcontent.IndexOf("<EOF>")>-1Then   'Allthedatahasbeenreadfromthe   'client.Displayitontheconsole.   Console.WriteLine("Read{0}bytesfromsocket."+vbLf+"Data:{1}",content.Length,content)   'Echothedatabacktotheclient.   Send(handler,content)   Else   'Notalldatareceived.Getmore.   handler.BeginReceive(state.buffer,0,StateObject.
BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)  
EndIf   EndIf   EndSub'ReadCallback     PrivateSharedSubSend(ByValhandlerAsSocket,ByValdataAsString)   'ConvertthestringdatatobytedatausingASCIIencoding.   DimbyteDataAsByte()=Encoding.ASCII.GetBytes(data)     'Beginsendingthedatatotheremotedevice.   handler.BeginSend(byteData,0,byteData.
Length,0,NewAsyncCallback(AddressOfSendCallback),handler)  
EndSub'Send     PrivateSharedSubSendCallback(ByValarAsIAsyncResult)   'Retrievethesocketfromthestateobject.   DimhandlerAsSocket=CType(ar.AsyncState,Socket)     'Completesendingthedatatotheremotedevice.   DimbytesSentAsInteger=handler.EndSend(ar)   Console.WriteLine("Sent{0}bytestoclient.",bytesSent)     handler.Shutdown(SocketShutdown.Both)   handler.Close()   'Signalthemainthreadtocontinue.   allDone.Set()   EndSub'SendCallback   EndClass'AsynchronousSocketListener 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.

【编辑推荐】

  1. 详细分析VB.NET WithEvents
  2. 浅析VB.NET局部静态变量
  3. 原理分析VB.NET开发控件
  4. 自己动手用代码实现VB.NET ListView加载数据
  5. 详细介绍VB.NET MyClass
责任编辑:佚名 来源: IT168
相关推荐

2009-10-22 15:23:32

VB.NET函数

2009-11-02 15:33:53

VB.NET Data

2009-10-27 16:05:52

VB.NET File

2014-02-27 10:27:46

PC远程维护

2021-12-15 14:39:50

LinuxGPG加解密文件

2021-08-04 08:55:02

Socket Java开发

2010-01-07 10:46:27

VB.NET Sock

2010-08-17 14:29:15

2009-10-23 17:03:18

VB.NET事件编程

2011-01-06 10:39:25

.NET程序打包

2009-11-02 15:16:07

VB.NET编程

2010-01-11 18:12:57

VB.NET使用MS

2015-07-28 14:27:44

2010-01-14 17:11:17

VB.NET枚举

2009-10-14 15:34:29

VB.NET窗体编程模

2009-11-02 15:08:58

VB.NET Obje

2009-11-10 13:08:13

VB.NET编程技巧

2009-11-02 14:55:52

VB.NET Obje

2009-11-10 15:30:46

VB.NET编程原则

2009-10-29 11:41:27

VB.NET写Obje
点赞
收藏

51CTO技术栈公众号