New to Socket Programming

SaintJimmy

Member
Joined
Jul 7, 2006
Messages
24
Programming Experience
5-10
For years I've been wanting to take the time to learn about network programming and sockets, and I've finally been able to take a look at it. I've found various learning resources on the net, but they all seem to use the same examples... "a simple chat program" or "a simple echo program". Basically all that happens is the client connects to the server, and the server sends back some text.

So here are some questions I have, if anyone could shed some light on these for me, I would be very grateful.

1.) Are there any examples anywhere (I can also program in C#, so samples in that language are ok too) that show an actual useful application of socket programming?

2.) Take a look at this example, because I'm going to use it to illustrate this next question. This is taken directly from the MSDN library under "Using TCP services". First is the client...

VB.NET:
Imports System
Imports System.Net.Sockets
Imports System.Text
 
Public Class TcpTimeClient
    Private const portNum As Integer = 13
    Private const hostName As String = "host.contoso.com"
 
    ' Entry point  that delegates to C-style main Private Function.
    Public Overloads Shared Sub Main()
        System.Environment.ExitCode = _
            Main(System.Environment.GetCommandLineArgs())
    End Sub
 
 
    Overloads Public Shared Function Main(args() As [String]) As Integer
        Try
            Dim client As New TcpClient(hostName, portNum)
 
            Dim ns As NetworkStream = client.GetStream()
 
            Dim bytes(1024) As Byte
            Dim bytesRead As Integer = ns.Read(bytes, 0, bytes.Length)
 
            Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead))
 
        Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try
 
        client.Close()
 
        Return 0
    End Function 'Main
End Class 'TcpTimeClient

Ok, and now the server....

VB.NET:
Imports System
Imports System.Net.Sockets
Imports System.Text
Public Class TcpTimeServer
 
    Private const portNum As Integer = 13
 
    ' Entry point that delegates to C-style main Private Function.
    Public Overloads Shared Sub Main()
        System.Environment.ExitCode = _
            Main(System.Environment.GetCommandLineArgs())
    End Sub
 
 
    Overloads Public Shared Function Main(args() As [String]) As Integer
        Dim done As Boolean = False
 
        Dim listener As New TcpListener(portNum)
 
        listener.Start()
 
        While Not done
            Console.Write("Waiting for connection...")
            Dim client As TcpClient = listener.AcceptTcpClient()
 
            Console.WriteLine("Connection accepted.")
            Dim ns As NetworkStream = client.GetStream()
 
            Dim byteTime As Byte() = _
                Encoding.ASCII.GetBytes(DateTime.Now.ToString())
 
            Try
                ns.Write(byteTime, 0, byteTime.Length)
                ns.Close()
                client.Close()
            Catch e As Exception
                Console.WriteLine(e.ToString())
            End Try
        End While
 
        listener.Stop()
 
        Return 0
    End Function 'Main
End Class 'TcpTimeServer

Now here's the thing I'm having trouble with... in this example the client initiates the connection and then immediately gets a NetworkStream object and starts reading. What if you're on a slow connection and you begin reading before the server sends back its response? And if you're programming for a scenario where the server may be handling a lot of traffic or the network connection may be slow (such as over the internet) and the response may not come back immediately, how do you handle something like that in code?
 
the client initiates the connection and then immediately gets a NetworkStream object
It doesn't immediately do anything unless a connection was made. This particular TcpClient constructor "makes a synchronous connection attempt" and "will block until it either connects or fails".

The Connect, Write and Read methods are synchronous (blocking calls) - the BeginConnect, BeginRead and BeginWrite methods are asynchronous.
 
NetworkStream.Read

Ok, that makes sense then. I didn't know that the Read operation would block until it actually gets something to read. I thought that if there was nothing to read it would just return 0.
 
Back
Top