Click here to Skip to main content
15,937,012 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
the client Application code
VB
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Drawing.Imaging
Imports System.Threading
Public Class Form1

    Private m_sock As Socket
    Private m_byBuff As Byte() = New Byte(36000) {}
    Dim byteDateLine As Byte()
    Dim data As IDataObject
    Private Sub frmWebCam_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            If m_sock IsNot Nothing AndAlso m_sock.Connected Then
                m_sock.Shutdown(SocketShutdown.Both)
                System.Threading.Thread.Sleep(10)
                m_sock.Close()
            End If
            m_sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim epServer As New IPEndPoint(IPAddress.Parse(txip.Text), 5502)
            m_sock.Blocking = False
            Dim onconnect__1 As New AsyncCallback(AddressOf OnConnect)
            m_sock.BeginConnect(epServer, onconnect__1, m_sock)
        Catch ex As Exception
        End Try
    End Sub
    Public Sub OnConnect(ByVal ar As IAsyncResult)
        Dim sock As Socket = DirectCast(ar.AsyncState, Socket)
        Try
            If sock.Connected Then
                SetupRecieveCallback(sock)
            Else
                MsgBox("Unable to connect to remote machine Connect Failed!")
            End If
        Catch ex As Exception
            MsgBox(ex.Message & "Unusual error during Connect!")
        End Try
    End Sub
    Public Sub OnRecievedData(ByVal ar As IAsyncResult)
        Dim sock As Socket = DirectCast(ar.AsyncState, Socket)
        Try
            Dim nBytesRec As Integer = sock.EndReceive(ar)
            If nBytesRec < 0 Then
                sock.Shutdown(SocketShutdown.Both)
                sock.Close()
            ElseIf nBytesRec > 0 Then
                Dim sRecieved As String = Encoding.ASCII.GetString(m_byBuff, 0, nBytesRec)
                MsgBox(sRecieved)
            End If

        Catch ex As Exception
        Finally
            SetupRecieveCallback(sock)
        End Try
    End Sub

    Public Sub SetupRecieveCallback(ByVal sock As Socket)
        Try
            Dim recieveData As New AsyncCallback(AddressOf OnRecievedData)
            sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock)
        Catch ex As Exception
            ' MessageBox.Show(Me, ex.Message, "Setup Recieve Callback failed!")
        End Try
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim DateLine As [Byte]() = Encoding.ASCII.GetBytes(Environment.MachineName & " :- " & txport.Text.ToCharArray())
        m_sock.Send(DateLine, DateLine.Length, 0)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            If m_sock IsNot Nothing AndAlso m_sock.Connected Then
                m_sock.Shutdown(SocketShutdown.Both)
                System.Threading.Thread.Sleep(10)
                m_sock.Close()
            End If
            m_sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim epServer As New IPEndPoint(IPAddress.Parse(txip.Text), 5502)
            m_sock.Blocking = False
            Dim onconnect__1 As New AsyncCallback(AddressOf OnConnect)
            m_sock.BeginConnect(epServer, onconnect__1, m_sock)
        Catch ex As Exception
        End Try
    End Sub
End Class

server side service code( At static IP)
VB
Imports System.Net.Sockets
Imports System.Net
Imports System.Threading

Public Class Service1
    Dim WithEvents atimer As New System.Timers.Timer(760)
    Public Shared m_aryClients As New ArrayList()
    Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    Protected Overrides Sub OnStart(ByVal args() As String)
    End Sub
    Private Sub TIMTICK(ByVal o As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles atimer.Elapsed
    End Sub
    Public Sub New()
        InitializeComponent()
        listener.Bind(New IPEndPoint(Dns.Resolve(System.Net.Dns.GetHostName).AddressList(0), 5502))
        listener.Listen(10)
        listener.BeginAccept(New AsyncCallback(AddressOf OnConnectRequest), listener)
        atimer.Start()
        atimer.Enabled = True
    End Sub

    Protected Overrides Sub OnStop()
        listener.Close()
    End Sub
    Public Sub OnConnectRequest(ByVal ar As IAsyncResult)
        Try
            Dim listener As Socket = DirectCast(ar.AsyncState, Socket)
            NewConnection(listener.EndAccept(ar))
            listener.BeginAccept(New AsyncCallback(AddressOf OnConnectRequest), listener)
        Catch ex As Exception

        End Try
    End Sub
    Public Sub NewConnection(ByVal sockClient As Socket)
        Try
            Dim client As New SocketChatClient(sockClient)
            m_aryClients.Add(client)
            client.SetupRecieveCallback(Me)

        Catch ex As Exception

        End Try
    End Sub
    Public Sub OnRecievedData(ByVal ar As IAsyncResult)
        Dim client As SocketChatClient = ar.AsyncState
        Dim aryRet = client.GetRecievedData(ar)
        Try
            If aryRet.Length < 1 Then
                client.Sock.Close()
                m_aryClients.Remove(client)
                Return
            Else
                For Each clientSend As SocketChatClient In m_aryClients
                    Try

                        clientSend.Sock.Send(aryRet, aryRet.Length, 0)
                    Catch
                        clientSend.Sock.Close()
                        m_aryClients.Remove(clientSend)
                    End Try
                Next
            End If
        Catch ex As Exception
        Finally
            client.SetupRecieveCallback(Me)
        End Try
    End Sub
    Friend Class SocketChatClient
        Private m_sock As Socket
        Private m_byBuff As Byte() = New Byte(36000) {}
        Public Sub New(ByVal sock As Socket)
            m_sock = sock
        End Sub
        Public ReadOnly Property Sock() As Socket
            Get
                Return m_sock
            End Get
        End Property
        Public Sub SetupRecieveCallback(ByVal app As Service1)
            Try
                Dim recieveData As New AsyncCallback(AddressOf app.OnRecievedData)
                m_sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, Me)
            Catch ex As Exception
                Console.WriteLine("Recieve callback setup failed! {0}", ex.Message)
            End Try
        End Sub
        Public Function GetRecievedData(ByVal ar As IAsyncResult) As Byte()
            Dim nBytesRec As Integer = 0
            Try
                nBytesRec = m_sock.EndReceive(ar)
            Catch
            End Try
            Dim byReturn As Byte() = New Byte(nBytesRec - 1) {}
            Array.Copy(m_byBuff, byReturn, nBytesRec)
            Return byReturn
        End Function
    End Class
End Class

but on server side i have two LAN Card one for LAN and other For WAN(Static IP) or internet so how can i communicate directly on WAN Card by static ip.

ON Server there two lan card
one has IP Address is 192.168.0.2
and
second has ip address is 292.268.154.54(Airtel Provide Static IP)

now i want to communicate by two different pc which has client code exe and different Network connection , so there is problem on connection b/w them

Please Help me
Posted
Updated 31-Aug-12 19:13pm
v3

1 solution

This function will return a list of IpV4 addresses in your machine.

VB
Private Function GetLocalIpAddresses() As List(Of System.Net.IPAddress)
      Dim strHostName As String
      Dim addresses() As System.Net.IPAddress
      Dim retAddresses As New List(Of System.Net.IPAddress)

      strHostName = System.Net.Dns.GetHostName()
      addresses = System.Net.Dns.GetHostAddresses(strHostName)

      ' Find an IpV4 address
      For Each address As System.Net.IPAddress In addresses
          If address.ToString.Contains(".") then
              retAddresses.Add(address)
          End If
      Next

      ' No IpV4 address? Return the loopback address.
      If retAddresses.Count = 0 Then retAddresses.Add(System.Net.IPAddress.Loopback)

      Return retAddresses
  End Function


After you have the list, you just decide which one you want to use.

You would replace

VB
listener.Bind(New IPEndPoint(Dns.Resolve(System.Net.Dns.GetHostName).AddressList(0), 5502))


with something like:

VB
Dim addresses As List(Of System.Net.IPAddress)
addresses = GetLocalIpAddresses()

' Lets say you know you want to use the first address...
listener.Bind(addresses.Item(0), 5502))


Also, you can just use my client and server classes to do communication over tcp/ip. Have a look at the project here.

Hope this helps... and if this is your answer, please hit the green button.

- Pete
 
Share this answer
 
v3
Comments
ravi kumar86 31-Aug-12 9:32am    
Can i create socket object by local ip address or remote ip address combination
like a teamviewer doing ?
please guid me how it is work?
pdoxtader 31-Aug-12 10:48am    
I'm sorry... I don't understand what you're asking. Of course you can create a socket using a local ip address... and you can connect to a remote ip address also... combination? If you want to do both, then do both. Listen on an ip / port in one thread, and connect to a remote machine on another.

Again, rather then code all this yourself, you'd be better off using the classes I've made available here ob CP. Good luck... and if this was your answer, please mark it as your solution.

- Pete
ravi kumar86 1-Sep-12 0:46am    
i am just asking about TCP/UDP hole punching on server side code , when two Client A,B are communicate each other.

You just go through this link:
http://www.brynosaurus.com/pub/net/p2pnat/

and tell how can i implement this technique on server sider windows service, which is given in my code
pdoxtader 1-Sep-12 9:12am    
There are several methods listed and explained in this article. I could ask you which one you wanted to be shown, but in my opinion they're all hacky, and the hackier ones aren't likely to work in all networks. Bryan (your article's author) says: "about 64% (of routers) support hole punching for TCP". Do you really want your app to work only 64% of the time?

The only one worth considering, in my opinion, is relaying.

A relay is a server that sits on the internet somewhere. It's not behind a nat (or has ports forwarded to it through a router). It will accept incoming connections, and relay data between two connected clients. I think you already understand this concept, and have what you need to build a relay if you want to, but you'd rather do something like connection reversal to save yourself the trouble.

Unfortunately I can't, in good conscience, show you how to circumvent people's network security, because contrary to what your article says punching holes IS compromising network security and CAN be used for nefarious purposes. It seems like you're interested in building a p2p app, but even uTorrent doesn't do "Hole Punching". uTorrent simply refuses to allow you to download anything unless you configure your router and forward port 22490 to the machine running uTorrent.

It's never a good idea to circumvent people's network security. It won't always work, and your app (and you) will get a bad reputation. Instead, require people to configure their network if they want to use your app. Offer help and guidance. That's the way the pros do it, anyway.

I suggest you take the same approach. Good luck.

- Pete

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900