Herewith is a sample write a socket with visual basic.NET 2005, the application is chat with multi user. the socket in VB 6.0 and Visual basic .NET have big diffrent. On .NET we can write socket with thread technique.
In .NET system class library includes a namespace for working with TCP Sockets, the system.net.sockets namespace. The server application, consist 1 form, and two classes. the socket using TCP listener and code for listener is like below ;
Try
SListener = New TcpListener(Net.IPAddress.Any, SwitchPort)
SListener.Start()
Me.IsServerStarted = True
Do Until IsServerStarted = False
'Thread.Sleep(50)
Dim XClient As New RSockClient(SListener.AcceptSocket)
AddHandler XClient.Connected, AddressOf OnConnected
AddHandler XClient.Disconnected, AddressOf OnDisconnected
AddHandler XClient.LineReceived, AddressOf OnIncoming
AddHandler XClient.LineSend, AddressOf OnSend
SID.Add(XClient.ID, XClient)
RaiseEvent ServerStatus("Connection Accepted From = " & XClient.ID)
RaiseEvent Connected(XClient.ID)
Loop
Catch ex As Exception
RaiseEvent ServerStatus(ex.Message)
End Try
on .Net if we use thread and want access to the form! like textbox or label, we cannot access directly. the error will be raised and say the thread is not safe. from MSDN if found how to handle error like this. we must use delegate method to avoid non thread safe. you can see at my code sample which i put on here , any comment is welcome.

0 komentar:
Post a Comment