Torna al Thread

Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary Imports System.Net.Sockets Imports System.Net.Sockets.TcpClient Imports System.Net Imports System Public Class Form1 Private moTcpClient, moTcpRxClient As TcpClient Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim moTcpServer = New TcpListener(13000) moTcpServer.Start() lb1.Text = ("Listening...") Button3.Enabled = False Button2.Enabled = True Button1.Enabled = False Do While Not moTcpServer.Pending Application.DoEvents() Loop moTcpRxClient = moTcpServer.AcceptTcpClient lb1.Text = ("Connection received...") moTcpServer.Stop() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim moLocalIP = Dns.GetHostByName(Dns.GetHostName) Dim ip = moLocalIP.AddressList(0).ToString '// Creates object Dim oPerson As New Person(TextBox1.Text, Int32.Parse(TextBox2.Text)) '// Let's use dotNET TcpClient moTcpClient = New TcpClient() moTcpClient.Connect(ip, 13000) If moTcpClient.GetStream.CanWrite Then '// Serializes object in memory Dim bf As New BinaryFormatter() Dim oStream As New System.IO.MemoryStream() bf.Serialize(oStream, oPerson) '// Gets bytes... Dim buf(CInt(oStream.Length)) As Byte oStream.Position = 0 Dim iRet As Int32 = oStream.Read(buf, 0, buf.Length) oStream.Close() '// Send object through TCP-IP... moTcpClient.GetStream.Write(buf, 0, buf.Length) Button3.Enabled = True Button2.Enabled = False End If End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click '// Deserializes object Dim oNs As NetworkStream = moTcpRxClient.GetStream If oNs.CanRead Then If oNs.DataAvailable Then '// Deserializes object Try Dim bf As New BinaryFormatter() Dim oRxPerson As Person = CType(bf.Deserialize(oNs), Person) Risultato.Text = String.Format("Name:{0} Age:{1}", oRxPerson.Name, oRxPerson.Age) Catch ex As Exception '// Something wrong... MessageBox.Show(ex.Message, "Deserialization error", MessageBoxButtons.OK, MessageBoxIcon.Error) Finally '// Closes connection moTcpRxClient.Close() ' btnDeser.Enabled = False Button3.Enabled = False Button2.Enabled = False Button1.Enabled = True End Try End If End If End Sub End Class '// Just a simple person object... <Serializable()> Public Class Person Public Name As String Public Age As Int32 Public Sub New(ByVal name As String, ByVal age As Int32) Me.Name = name Me.Age = age End Sub End Class
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5