手把手指導VB.NET Socket編程
作者:佚名
這里介紹一直以來很想學習VB.NET Socket編程方面的應用,比如怎樣通過VB.NET Socket編程實現(xiàn)單片機與PC的TCP連接通信。
VB.NET經過長時間的發(fā)展,很多用戶都很了解VB.NET Socket編程了,這里我發(fā)表一下個人理解,和大家討論討論。一直以來很想學習VB.NET Socket編程方面的應用,比如怎樣通過VB.NET Socket編程實現(xiàn)單片機與PC的TCP連接通信。在單片機嵌入網卡芯片與PC進行連接通信,實現(xiàn)PC的web方式對單片機所控制的設備的狀態(tài)管理,例如智能家居方面的應用。
下面通過例子來學習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
【編輯推薦】
責任編輯:佚名
來源:
IT168