#眉標=.NET Namespace專欄 #副標=.System.Xml.Serialization #大標=網路通訊作業─Socket和TcpClient #作者=文/彭靖灝 =======程式======= 程式1 Dim mySocket As Socket mySocket = New Socket(AddressFamily.InterNetwork, _ SocketType.Stream, ProtocolType.Tcp) =======程式======= =======程式======= 程式2 Dim LocalAddress As IPAddress = _ IPAddress.Parse("127.0.0.1") Dim LocalEndPoint = New IPEndPoint_ (LocalAddress, 11000) MainSocket.Bind(LocalEndPoint) =======程式======= =======程式======= 程式3 Dim RemoteAddress As IPAddress RemoteAddress = _ Dns.GetHostEntry("MyHost”).AddressList(0) Dim RemoteEndPoint As IPEndPoint RemoteEndPoint = New IPEndPoint(RemoteAddress, _ 12000) mySocket.Connect(RemoteEndPoint) =======程式======= =======程式======= 程式4 Dim Encoder As New UTF8Encoding Dim myMessage As Byte() = Encoder.GetBytes _ (txtData.Text) If mySocket.Connected Then mySocket.Send(myMessage) End If =======程式======= =======程式======= MainSocket.Listen(10) =======程式======= =======程式======= 程式5 Dim MySocket As Socket MySocket = MainSocket.Accept Console.WriteLine("Connected: {0}", _ MySocket.RemoteEndPoint) ' 進行作業…. MySocket.Close() =======程式======= =======程式======= MySocket.Receive(BufferArray, BufferArray.Length, 0) =======程式======= =======程式======= 程式6 =======程式======= =======程式======= 程式7利用Socket接收要求並回應 Imports System Imports System.Threading Imports System.IO Imports System.Net Imports System.Net.Sockets Imports System.Configuration Module MyListener Dim MainSocket As Socket Const LIMIT = 5 Sub Main() Dim i As Integer MainSocket = New Socket(AddressFamily.InterNetwork, _ SocketType.Stream, ProtocolType.Tcp) Dim LocalAddress As IPAddress = _ Dns.GetHostAddresses(Dns.GetHostName)(0) Dim LocalEndPoint = New IPEndPoint(LocalAddress, 11000) MainSocket.Bind(LocalEndPoint) MainSocket.Listen(LIMIT) Console.WriteLine("Server mounted, listening to port 11000") Dim t As Thread t = New Thread(New ThreadStart(AddressOf MyService)) t.Start() End Sub Private Sub MyService() Dim MySocket As Socket MySocket = MainSocket.Accept Console.WriteLine("Connected: {0}", _ MySocket.RemoteEndPoint) Try Dim s As Stream = New NetworkStream(MySocket) Dim sr As StreamReader = New StreamReader(s) Dim sw As StreamWriter = New StreamWriter(s) sw.AutoFlush = True ' enable automatic flushing sw.WriteLine("{0} Employees available", _ ConfigurationManager.AppSettings.Count) Do While True Dim TheName As String = sr.ReadLine() If TheName = "" Or (TheName Is Nothing) Then Exit Do End If Dim job As String = _ ConfigurationManager.AppSettings(TheName) If (job Is Nothing) Then job = "No such employee" sw.WriteLine(job) Loop s.Close() Catch ex As Exception Console.WriteLine(ex.Message) End Try Console.WriteLine("Disconnected: {0}", _ MySocket.RemoteEndPoint) MySocket.Close() End Sub End Module =======程式======= =======程式======= telnet localhost 11000 =======程式======= =======程式======= 程式8 Dim Listener As TcpListener Private Sub btnConnect_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles btnConnect.Click ' 建立本機的通訊端點 Dim LocalAddress As IPAddress LocalAddress = Dns.GetHostAddresses _ (Dns.GetHostName)(0) Dim LocalEndPoint As IPEndPoint LocalEndPoint = New IPEndPoint(LocalAddress, _ System.Int32.Parse(txtPortNo.Text)) ' 準備接聽器 Listener = New TcpListener(LocalEndPoint) Me.WriteMessage _ ("目前連接埠:" & LocalEndPoint.Port.ToString) Listener.Start() End Sub =======程式======= =======程式======= 程式9透過TcpListener接收資料 Dim MySocket As Socket Dim Listener As TcpListener Dim ListenThread As Thread Delegate Sub WriteMessageCallback(ByVal Message As String) Private Sub btnStartListen_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStartListen.Click ' 準備接收作業的thread ListenThread = New Thread(New ThreadStart(AddressOf MyService)) ListenThread.Start() btnStartListen.Enabled = False btnStopListen.Enabled = True btnConnect.Enabled = False End Sub Private Sub MyService() Dim ListenSocket As Socket 'MySocket = MyListener.AcceptSocket() ListenSocket = Listener.AcceptSocket Me.WriteMessage(String.Format("連結建立:{0}", _ ListenSocket.RemoteEndPoint)) Try Dim s As Stream = New NetworkStream(ListenSocket) Dim sr As StreamReader = New StreamReader(s) Dim sw As StreamWriter = New StreamWriter(s) sw.AutoFlush = True ' enable automatic flushing sw.WriteLine("{0} employee records", _ ConfigurationManager.AppSettings.Count) Do While True Dim EmpName As String = sr.ReadLine() If EmpName = "quit" Then sw.WriteLine("OK") Exit Do End If If EmpName = "" Or (EmpName Is Nothing) Then Exit Do Dim job As String = _ ConfigurationManager.AppSettings(EmpName) If (job Is Nothing) Then job = "No such employee" sw.WriteLine(job) Loop s.Close() Catch ex As Exception Console.WriteLine(ex.Message) End Try Me.WriteMessage(String.Format("中斷連結:{0}", _ ListenSocket.RemoteEndPoint)) ListenSocket.Close() End Sub Private Sub btnStopListen_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStopListen.Click ListenThread.Abort() btnStartListen.Enabled = True btnStopListen.Enabled = False btnConnect.Enabled = True End Sub Private Sub WriteMessage(ByVal Message As String) If Me.txtData.InvokeRequired Then Dim d As New WriteMessageCallback(AddressOf WriteMessage) Me.Invoke(d, New Object() {Message}) Else txtData.Text &= Message & vbNewLine End If End Sub =======程式======= =======程式======= 程式10 Private Sub btnConnect_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles btnConnect.Click Dim LocalAddress As IPAddress LocalAddress = IPAddress.Parse("127.0.0.1") Dim LocalEndPoint As New _ IPEndPoint(LocalAddress, 5700) If Not Client Is Nothing Then Client.Close() Client = Nothing End If Client = New TcpClient(LocalEndPoint) Client.Connect(txtRemoteAddress.Text, _ System.Int32.Parse(txtPortNo.Text)) End Sub =======程式======= =======程式======= 程式11 Private Sub btnSendData_Click _ (ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnSendData.Click Dim s As Stream Dim sr As StreamReader Dim sw As StreamWriter Try s = Client.GetStream sr = New StreamReader(s) sw = New StreamWriter(s) sw.AutoFlush = True WriteMessage("Name:" & txtMessage.Text) sw.WriteLine(txtMessage.Text) WriteMessage(sr.ReadLine()) Catch ex As Exception WriteMessage("Error:" & ex.Message) End Try End Sub =======程式=======