Here is an example. Create a new windows app, add a checkbox a listbox and
a button. Start the app and check the checkbox to start the server (clear
it to shut the server down). Once the server has started click the button
to serialise/deseleralise the object through the socket. Obviously this
works standalone, but start two instances of the app and click the server
checkbox on one and press the button on the other and you'll see the exact
same code sending the object to a different app. This app could even be on
another machine.
Error handling etc is incredibly thin on the ground, this is just a demo.
Any comments welcome cos I'm still a .net noob myself
If you plan on
using this kind of idea it is better to create a self-contained listener
object rather than hacking it the way I have here so that everything runs
from the one form. This is .net 1.1 and seems a bit different to how things
worked in 1.0 IIRC.
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Xml.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Net.Sockets
Imports System.Net
Public Class Form1
Inherits System.Windows.Forms.Form
Private Delegate Sub UpdateListBoxDel(ByVal Data As String)
Private m_ListenerThread As Threading.Thread
Private server As New TcpListener(IPAddress.Parse("127.0.0.1"), 5000)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
' Create a new object that is populated with data
Dim obj As New MyObject(1, "Adrian", "Forbes")
' Create an XmlSerializer for the MyObject type
Dim formatter As New XmlSerializer(GetType(MyObject))
' Create new TcpClient
Dim client As TcpClient = New TcpClient
' Connect to port 5000 on the local machine
UpdateDisplay("Connecting to client", True)
client.Connect("127.0.0.1", 5000)
' Get the underlying stream
Dim stream As Stream = client.GetStream
' Seralise out instance of MyObject over the TcpClient's stream
using the XmlSerializer
UpdateDisplay("Sending..." & obj.ToString, True)
formatter.Serialize(stream, obj)
' Close the stream
stream.Close()
End Sub
Private Sub StartServer()
' This function is going to run until the server closes
' so set up a var that lets us know we want to run
Dim bRunning As Boolean = True
' Start the server
UpdateDisplay("Server starting")
server.Start()
While bRunning
Try
' This method will block until a connection is accepted
UpdateDisplay("Server waiting for connection...")
Dim client As TcpClient = server.AcceptTcpClient()
' Now we have a TcpClient with an underlying stream
' so we want to deserialise our object. This is
' pretty much the sending code in reverse.
UpdateDisplay("Server connected")
Dim Formatter As XmlSerializer = New
XmlSerializer(GetType(MyObject))
Dim obj As MyObject =
CType(Formatter.Deserialize(client.GetStream), MyObject)
UpdateDisplay("Received " & obj.ToString)
Catch
' If we get an error such as the connection getting
' closed from under us then signal to stop running
bRunning = False
End Try
End While
' Stop the server
Debug.WriteLine("Server stopping")
server.Stop()
End Sub
Private Sub UpdateDisplay(ByVal Data As String)
' Invoke a call to update the listbox
ListBox1.Invoke(New UpdateListBoxDel(AddressOf UpdateListBox), New
Object() {Data})
End Sub
Private Sub UpdateDisplay(ByVal Data As String, ByVal Direct As Boolean)
If Direct Then
' This method will update the listbox on this thread
UpdateListBox(Data)
Else
' Otherwise use this method that will use the listbox's thread
to
' do the update
UpdateDisplay(Data)
End If
End Sub
Public Sub UpdateListBox(ByVal Data As String)
ListBox1.Items.Add(Data)
Application.DoEvents()
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not m_ListenerThread Is Nothing Then
' If the TcpListener is listening then shut it down
StopServer()
End If
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
' The server checkbox has been clicked so kick off a new thread
' and run our StartServer method on it
UpdateDisplay("Starting server")
m_ListenerThread = New Threading.Thread(AddressOf StartServer)
m_ListenerThread.Start()
UpdateDisplay("Started")
Else
' The checkbox has been unchecked so shut the server down
UpdateDisplay("Stopping server", True)
StopServer()
UpdateDisplay("Stopped", True)
End If
End Sub
Private Sub StopServer()
' Stop the TcpListener
server.Stop()
' and wait here for the thread to exit. The above call will cause
an
' exception in the listener thread so lets just wait until it is all
' closed up
m_ListenerThread.Join()
End Sub
End Class
<Serializable()> _
Public Class MyObject
Public EmployeeID As Long
Public Forename As String
Public Surname As String
Public Sub New(ByVal EmployeeID As Long, ByVal Forename As String, ByVal
Surname As String)
Me.EmployeeID = EmployeeID
Me.Forename = Forename
Me.Surname = Surname
End Sub
Public Sub New()
Me.EmployeeID = 0
Me.Forename = ""
Me.Surname = ""
End Sub
Public Overrides Function ToString() As String
Return EmployeeID.ToString & ": " & Surname & ", " & Forename
End Function
End Class