Class ChatMain Public Shared Sub Main(ByVal args As String()) Dim srv As Server = New Server srv.Run End Sub End Class
Class Server Private allclients As ArrayList
Public Sub Run() allclients = New ArrayList Dim server As TcpListener = New TcpListener(IPAddress.Any, 50000) server.Start While True Dim client As TcpClient = server.AcceptTcpClient Dim ch As ClientHandler = New ClientHandler(client, Me) allclients.Add(ch) Call (New Thread(AddressOf ch.Run)).Start End While End Sub
Public Sub SendAll(ByVal msg As String) For Each ch As ClientHandler In allclients ch.Send(msg) Next End Sub
Public Sub Remove(ByVal ch As ClientHandler) allclients.Remove(ch) End Sub End Class
Class ClientHandler Private rdr As StreamReader Private wrt As StreamWriter Private srv As Server
Public Sub New(ByVal cli As TcpClient, ByVal srv As Server) rdr = New StreamReader(cli.GetStream) wrt = New StreamWriter(cli.GetStream) Me.srv = srv End Sub
Public Sub Run() While True Dim line As String = rdr.ReadLine Dim cmd As String = line.Split(" ".ToCharArray)(0) If cmd = "SEND" Then srv.SendAll(line.Substring(5)) Else If cmd = "EXIT" Then srv.Remove(Me) Return End If End If End While End Sub
Public Sub Send(ByVal msg As String) SyncLock wrt wrt.WriteLine(msg) wrt.Flush End SyncLock End Sub End Class
Imports System Imports System.IO Imports System.Net.Sockets Imports System.Threading
Class ChatClient Public Shared Sub Main(ByVal args As String()) Dim client As TcpClient = New TcpClient("localhost", 50000) Dim wrt As StreamWriter = New StreamWriter(client.GetStream) Call (New Thread(AddressOf (New Reader(client)).Run)).Start Dim line As String line = Console.ReadLine While Not (line Is Nothing) wrt.WriteLine("SEND " + line) wrt.Flush line = Console.ReadLine End While wrt.WriteLine("EXIT") wrt.Flush wrt.Close client.Close End Sub End Class
Class Reader Private rdr As StreamReader
Public Sub New(ByVal cli As TcpClient) rdr = New StreamReader(cli.GetStream) End Sub
Public Sub Run() Try Dim line As String line = rdr.ReadLine While Not (line Is Nothing) Console.WriteLine(line) line = rdr.ReadLine End While Catch e As Exception ' nothing End Try End Sub End Class
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.