vb.net で LAN ベースのアプリケーションを作成しています。すでにサーバーとクライアントを作成しており、両方のプログラマーのリリース ビルドを作成しています。
サーバーコード
Imports System.Net
Imports System.Net.Sockets
Module Module1
Dim isActive As Boolean
Sub Main()
Dim port As Integer 'this is port number
Dim localAddr As IPAddress 'Ip Address
Dim server As TcpListener ' for use tcp/ip protocol
Dim client As TcpClient
Dim aString As String
Dim negotiateStream As Security.NegotiateStream = Nothing
Dim d As DictionaryEntry
Try
port = 8888
localAddr = IPAddress.Loopback 'return the ipaddress of self
'creating the server
server = New TcpListener(localAddr, port)
server.Start()
Console.WriteLine("Server ready")
'this is a block method, it will wait for new connection
'before continuing
client = server.AcceptTcpClient
Console.WriteLine("Connected to " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString)
Console.WriteLine("Connected to " & client.ToString)
Do
Console.Write(" Ready to quit? (y/n)")
aString = Console.ReadLine()
If aString <> "y" Then
'do something
End If
Loop Until aString = "y" ' Or aString = "n"
Catch e As System.Exception
Console.WriteLine("Can't create the server : " + e.Message)
End Try
End Sub
End Module
クライアントコード
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Imports System.Text
Public Class Form1
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim networkStream As NetworkStream 'use to send/recieve data
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ConnectToServer(localAddr, port)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Press button to connect with the server"
port = 8888
localAddr = IPAddress.Loopback
Button2.Enabled = False
End Sub
Private Sub ConnectToServer(ByRef ipaddr, ByRef port)
Try
client = New TcpClient(localAddr.ToString, port)
TextBox1.Text = "Connencted to : " & IPAddress.Parse(CType(client.Client.LocalEndPoint, IPEndPoint).Address.ToString).ToString & " "
networkStream = client.GetStream()
Button1.Enabled = False
Button2.Enabled = True
Catch e As Exception
MsgBox(e.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("Message from Client$")
networkStream.Write(outStream, 0, outStream.Length)
networkStream.Flush()
End Sub
End Class
サーバーを起動してclient1をサーバーに接続すると、サーバーのコンソールに「connect to client _」のようなメッセージが出力されますが、別のクライアント(client2)を開いてサーバーに接続すると、新しいメッセージは表示されませんクライアント用 2。