Share via


Send and Receive Data Through Sockets

Question

Wednesday, December 3, 2008 11:41 AM

Hey,
I'm completely new to sockets etc.
I'm trying to create an app that'll allow someone to send short information messages to several other people with the same app, using the internet and sockets(?)

I've tried using code from online, but I'm getting no where. Could anyone help me please?

I'm using Visual Studio Express 2008 Visual Basic. Any help would be great.

Thanks

All replies (3)

Wednesday, December 10, 2008 2:18 AM ✅Answered

Shaun4 said:
I'm completely new to sockets etc.
I'm trying to create an app that'll allow someone to send short information messages to several other people with the same app, using the internet and sockets(?)

Hi Shaun,

Welcome to MSDN forums!

Based on my understanding, you intend to make an Online Chat Application.

Firstly, .NET has native implementation for socket communication. The namespace System.Net.Sockets contains most of the objects required for socket communication.

Here is one good source-opened Chat Application for you to download and check, which uses System.Net.Sockets namespace instead of VB6 WinSock control.

Creating a Multi-User TCP Chat Application

http://msdn2.microsoft.com/en-us/library/aa478452.aspx
It's written in VB.NET. Download the Vbsockets.exe sample file, then run and unzip it, you will find two projects: SocketClient and SocketServer.
 
  

Other examples:
A simple TCP/IP Chat client/server
TCP/IP Chat Application Using .NET

Additionally, there is one source-opened Winsock.NET control similar to VB6 Winsock.
http://www.codeproject.com/KB/vb/winsockdotnet.aspx

By the way, the .NET Framework Networking and Communication forum is more appropriate for such issues.

Best regards,
Martin Xie


Wednesday, December 10, 2008 2:21 AM ✅Answered | 1 vote

Hi shaun4,

The following code example shows how the Socket class can be used to send data to an HTTP server and receive the response. This example blocks until the entire page is received

Public Class GetSocket  
 
   Private Shared Function ConnectSocket(server As String, port As Integer) As Socket  
      Dim s As Socket = Nothing 
      Dim hostEntry As IPHostEntry = Nothing        
 
         ' Get host related information.  
        hostEntry = Dns.GetHostEntry(server)  
 
         ' Loop through the AddressList to obtain the supported AddressFamily. This is to avoid  
         ' an exception that occurs when the host host IP Address is not compatible with the address family  
         ' (typical in the IPv6 case).  
      Dim address As IPAddress  
 
        For Each address In  hostEntry.AddressList  
            Dim endPoint As New IPEndPoint(address, port)  
            Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)  
 
            tempSocket.Connect(endPoint)  
 
            If tempSocket.Connected Then  
               s = tempSocket 
               Exit For  
            End If  
 
         Next address  
 
      Return s  
   End Function   
 
 
   ' This method requests the home page content for the specified server.  
 
   Private Shared Function SocketSendReceive(server As String, port As Integer) As String  
      'Set up variables and String to write to the server.  
      Dim ascii As EncodingEncoding = Encoding.ASCII  
      Dim request As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf  
      Dim bytesSent As [Byte]() = ascii.GetBytes(request)  
      Dim bytesReceived(255) As [Byte]  
 
      ' Create a socket connection with the specified server and port.  
      Dim s As Socket = ConnectSocket(server, port)  
 
      If s Is Nothing Then  
         Return "Connection failed"  
      End If   
      ' Send request to the server.  
      s.Send(bytesSent, bytesSent.Length, 0)  
 
      ' Receive the server  home page content.  
      Dim bytes As Int32  
 
      ' Read the first 256 bytes.  
      Dim page as [String] = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf  
 
      ' The following will block until the page is transmitted.  
      Do  
         bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)  
            pagepage = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes)  
      Loop While bytes > 0  
 
      Return page  
   End Function   
 
   'Entry point which delegates to C-style main Private Function  
   Public Overloads Shared Sub Main()  
      Main(System.Environment.GetCommandLineArgs())  
   End Sub  
 
 
   Overloads Private Shared Sub Main(args() As String)  
      Dim host As String  
      Dim port As Integer = 80 
 
      If args.Length = 1 Then  
         ' If no server name is passed as argument to this program,   
         ' use the current host name as default.  
         host = Dns.GetHostName()  
      Else  
         host = args(1)  
      End If   
 
      Dim result As String = SocketSendReceive(host, port)  
 
      Console.WriteLine(result)  
   End Sub 'Main  
End Class    
 
 

I think these article could help you.
http://www.codeproject.com/KB/IP/mailclient.aspx

Link:
http://forums.vbcity.com/forums/faq.asp?fid=15&cat=Networking&#TID145140

Sending the messages over TCP/IP requires the use of Sockets, which have been nicely wrapped in .NET by the System.Net.Sockets class, and is as simple as calling the Connect and Send methods using the proper parameters. The following code will send a text message ("Hello World!") to the computer using the local IP address "192.168.2.106": 

 Try   
            Dim clsError As System.Net.Sockets.SocketError   
            Dim bMessage As Byte() = System.Text.Encoding.ASCII.GetBytes("Hello World!")   
            Dim clsSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)   
            clsSocket.Connect("192.168.2.106", 1972)   
            clsSocket.Send(bMessage, 0, bMessage.Length, SocketFlags.None, clsError)   
            If clsError = SocketError.Success Then   
                MessageBox.Show(Me, "Message sent!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information)   
            Else   
                MessageBox.Show(Me, "The message was not sent successfully, the message was: " & clsError.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)   
            End If   
        Catch ex As Exception   
            MessageBox.Show(Me, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)   
        End Try               
 
 

Receiving these messages requires the use of the same objects, but in different ways:

 ' create listener socket...   
            Dim clsEndpoint As IPEndPoint = New IPEndPoint(New IPAddress(New Byte() {192, 168, 2, 106}), 1972)   
            Dim clsServerSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)   
            ' bind to the IP address and port - this blocks other listeners from using the same combination...   
            clsServerSocket.Bind(clsEndpoint)   
            ' listen for incoming connections...   
            clsServerSocket.Listen(CInt(Fix(SocketOptionName.MaxConnections)))   
            Do   
                ' poll for connections - this allows us to keep listening so the thread doesn't block...   
                If clsServerSocket.Poll(10000, SelectMode.SelectRead) Then   
                    ' a message is being sent - create a socket to read it...   
                    Dim clsSocket As Socket = clsServerSocket.Accept()   
                    ' read the message from the buffer...   
                    Dim bReadBuffer As Byte() = New Byte(255) {}   
                    clsSocket.Receive(bReadBuffer, bReadBuffer.Length, SocketFlags.None)   
                    ' convert to a string...   
                    Dim sMessage As String = ""   
                    sMessage = System.Text.Encoding.ASCII.GetString(bReadBuffer)   
                    'display message...   
                    MessageBox.Show(Me, sMessage, "Incoming Message", MessageBoxButtons.OK, MessageBoxIcon.Information)   
                    ' release socket...   
                    clsSocket.Close()   
                    clsSocket = Nothing   
                End If   
            Loop       
 

The above code will loop continually, always listening for incoming connections and displaying them in a MessageBox when they are received (of course, this action blocks the listening action and isn't practical in real life - it's just for the purposes of illustration).

Another limitation of the code above is that the message received can be no longer than 255 bytes. In order to send data longer (or shorter) than that, you would have to work some sort of data length indicator into your message and use the overload of the Receive method that accepts the Offset and Length parameters. For example, include the length of the text data in the first N characters of the message. If the text you wanted to send was:

"Hello World!"

...then you would instead send:

"0000000012Hello World!"

The first 10 digits in this case indicate how many more characters follow in the message. You could then create a buffer with a length of 10, call the Receive method that accepts an Offset and Length parameter (passing 0, and 10, respectively), read the value received and resize the buffer accordingly, and then call the Receive method again passing in the new Offset (10 and N - 10, respectively).

NOTE: The System.Net.Sockets namespace also provides TcpListener and TcpClient classes which provide similar functionailty, but I prefer to use the Sockets class directly as it enables you more control over the details of your send / receive communications.

If you have any issue, please feel free to tell us.
Best Wishes
Xingwei Hu
Please remember to mark the replies as answers if they help and unmark them if they provide no help.


Wednesday, December 10, 2008 10:14 AM

Thanks guys. I'll scrap the other one and use your suggestions. Really helpful, cos I had no clue what I was doing.

Thankyou

:D