VB.netにてTCP/IP接続
VB.net 2002用サーバー 2003の場合は下のほうにあります。
ーーーーサーバーーーーー
Sub Main()
Const portNum As Integer = 1000 '待機するポート番号を指定
Dim listener As New System.Net.Sockets.TcpListener(portNum)
listener.Start()
While True
Console.Write("Waiting for connection...")
Dim client As System.Net.Sockets.TcpClient = listener.AcceptTcpClient()
Console.WriteLine("Connection accepted.")
Dim ns As System.Net.Sockets.NetworkStream = client.GetStream()
'----送信部分----
Dim word As Byte() = System.Text.Encoding.Default.GetBytes("今日は")
ns.Write(word, 0, word.Length)
'----受信部分----
Dim getWord(1024) As Byte
Dim bytesRead As Integer = ns.Read(getWord, 0, getWord.Length)
Console.WriteLine(System.Text.Encoding.Default.GetString(getWord, 0, bytesRead))
ns.Close()
client.Close()
End While
listener.Stop()
End Sub
ーーーークライアントーーーー
VB.net 2002 2003ともに動きます
Sub Main()
Dim portNum As Integer = 1000 'ポート番号を指定
Dim hostName As String = "localhost" 'アドレスを指定
Dim client As New System.Net.Sockets.TcpClient(hostName, portNum)
Dim ns As System.Net.Sockets.NetworkStream = client.GetStream()
'----受信----
Dim bytes(1024) As Byte
Dim bytesRead As Integer = ns.Read(bytes, 0, bytes.Length)
Debug.WriteLine(System.Text.Encoding.Default.GetString(bytes, 0, bytesRead))
'----送信----
Dim word As Byte() = System.Text.Encoding.Default.GetBytes("晴天")
ns.Write(word, 0, word.Length)
ns.Close()
client.Close()
End Sub
-------------------------------------------------------------------------------------------------------
VB.net 2003では上のコードでは動きませんでした
以下が2003対応のコードです
ーーーーサーバーーーーー
Private Sub Thread1()
Dim portNum As Integer = 1000 '待機するポート番号を指定
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.Resolve(System.Net.Dns.GetHostName()).AddressList(0)
Dim ipLocalEndPoint As New System.Net.IPEndPoint(ipAddress, portNum)
Dim listener As New System.Net.Sockets.TcpListener(ipLocalEndPoint)
listener.Start()
While True
Console.Write("Waiting for connection...")
Dim client As System.Net.Sockets.TcpClient = listener.AcceptTcpClient()
Console.WriteLine("Connection accepted.")
Dim ns As System.Net.Sockets.NetworkStream = client.GetStream()
Try
'----送信部分----
Dim word As Byte() = System.Text.Encoding.Default.GetBytes("今日は")
ns.Write(word, 0, word.Length)
'----受信部分----
Dim getWord(1024) As Byte
Dim bytesRead As Integer = ns.Read(getWord, 0, getWord.Length)
TextBox1.Text = System.Text.Encoding.Default.GetString(getWord, 0, bytesRead)
Catch ex As Exception
Console.WriteLine("err : " + ex.ToString)
End Try
ns.Close()
client.Close()
End While
listener.Stop()
End Sub