' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets

Namespace SocketDemo.Text.High.SingleServer
    Public Class Program
        Private Const PORT As Integer = 12345
        Private Const BACKLOG As Integer = 100
        Public Shared Sub Main(args As String())
            ' listen on port
            Dim srv As New TcpListener(IPAddress.Any, PORT)
            srv.Start(BACKLOG)
            While True
                ' accept connection
                Dim cli As TcpClient = srv.AcceptTcpClient()
                ' get reader and writer
                Dim stm As NetworkStream = cli.GetStream()
                Dim sr As New StreamReader(stm)
                Dim sw As New StreamWriter(stm)
                Console.WriteLine("(connection from {0})", cli.Client.RemoteEndPoint)
                ' read a and b
                Dim line As String = sr.ReadLine()
                Dim parts As String() = line.Split(" "C)
                Dim a As Integer = Integer.Parse(parts(0))
                Dim b As Integer = Integer.Parse(parts(1))
                ' calculate c and send
                Dim c As Integer = a + b
                sw.WriteLine(c)
                sw.Flush()
                ' read v
                Dim v As String = sr.ReadLine()
                ' calculate v2 and send
                Dim v2 As String = v & v
                sw.WriteLIne(v2)
                sw.Flush()
                ' close connection
                sr.Close()
                sw.Close()
                cli.Close()
            End While
        End Sub
    End Class
End Namespace
