By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,333 Members | 1,060 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,333 IT Pros & Developers. It's quick & easy.

TCPListener

P: n/a
hi i have a working code for a tcpclient, but i cant seemt of figure out how
to use a tcplistener to connect with it. i just want to clck a button and
listen for a TCP conection and conect to a specific port, but any attempt i
try fails....any help would b awsome
--
-iwdu15
Nov 21 '05 #1
Share this Question
Share on Google+
23 Replies


P: n/a
Send your code to see what we can do

-----Original Message-----
From: iwdu15 [mailto:iw****@discussions.microsoft.com]
Posted At: Wednesday, September 28, 2005 10:37 PM
Posted To: microsoft.public.dotnet.languages.vb
Conversation: TCPListener
Subject: TCPListener

hi i have a working code for a tcpclient, but i cant seemt of figure out
how
to use a tcplistener to connect with it. i just want to clck a button
and
listen for a TCP conection and conect to a specific port, but any
attempt i
try fails....any help would b awsome
--
-iwdu15

Nov 21 '05 #2

P: n/a
ok, heres the code i tried for listening async:

#Region "Declarations"

Dim homeip As Net.IPAddress
Dim ClientSocket As Net.Sockets.Socket
Dim ASCII As New System.Text.ASCIIEncoding

Dim ListenSocket As Net.Sockets.Socket

#End Region

#Region "Listen"

Private Sub btnlisten_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnlisten.Click

Call Listen(homeip, Me.txtlistenport.Text)

End Sub

Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)

ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub

Private Sub ListenCallBack(ByVal ar As IAsyncResult)

Try
ListenSocket.EndAccept(ar)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Sub ListenReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

If numbytes = 0 Then

ListenSocket.Shutdown(SocketShutdown.Both)
ListenSocket.Close()

Else

Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Begin Receive Again
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

End If

End Sub

#End Region

thanks

-iwdu15
Nov 21 '05 #3

P: n/a
Hi,

A few comments about your code.

1. I don't see whether you assigned something to homeip.
2. I don't see if you bound ListenSocket to homeip, and put it into
listening state.
3. I don't see where you assigned something to ClientSocket before
receiving data from it.
4. In ListenReceiveCallBack routine you call EndReceive from
ListenSocket, not ClientSocket.

So,

1.Assign something to homeip. For example, IPAddress.Any.
2. Insert ~ ListenSocket.Bind(ep) ~ and ~ ListenSocket.Listen(0) ~ prior
to call to ListenSocket.BeginAccept().
3. Change ~ ListenSocket.EndAccept(ar) ~ to ~ ClientSocket =
ListenSocket.EndAccept(ar) ~.
4. Change ~ ListenSocket.EndReceive ~ to ~ ClientSocket.EndReceive ~.

Hope this helps,
Roman

"iwdu15" <iw****@discussions.microsoft.com> сообщил/сообщила в новостях
следующее: news:B4**********************************@microsof t.com...
ok, heres the code i tried for listening async:

#Region "Declarations"

Dim homeip As Net.IPAddress
Dim ClientSocket As Net.Sockets.Socket
Dim ASCII As New System.Text.ASCIIEncoding

Dim ListenSocket As Net.Sockets.Socket

#End Region

#Region "Listen"

Private Sub btnlisten_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlisten.Click

Call Listen(homeip, Me.txtlistenport.Text)

End Sub

Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub

Private Sub ListenCallBack(ByVal ar As IAsyncResult)

Try
ListenSocket.EndAccept(ar)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Sub ListenReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

If numbytes = 0 Then

ListenSocket.Shutdown(SocketShutdown.Both)
ListenSocket.Close()

Else

Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Begin Receive Again
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

End If

End Sub

#End Region

thanks

-iwdu15

Nov 21 '05 #4

P: n/a
www.vbip.com
there is tutorial or use some googlle search

iwdu15 wrote:
hi i have a working code for a tcpclient, but i cant seemt of figure out how
to use a tcplistener to connect with it. i just want to clck a button and
listen for a TCP conection and conect to a specific port, but any attempt i
try fails....any help would b awsome

Nov 21 '05 #5

P: n/a
well that wasnt all my code, that was just relavant to the listening paert,
if u want i can show all my code, but homeip is used in the formload event to
get the IP address from the computer its running on, and clientsocket wis
used to send the connect request in my other code and the code endrecieve is
in there, il just list all my code here:

#Region "Declarations"

Dim homeip As Net.IPAddress
Dim ClientSocket As Net.Sockets.Socket
Dim ASCII As New System.Text.ASCIIEncoding

Dim ListenSocket As Net.Sockets.Socket

#End Region

#Region "Connect"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

homeip =
Net.Dns.GetHostByName(Net.Dns.GetHostName).Address List.GetValue(0)

Me.Text = homeip.ToString

End Sub

Private Sub btnconnect_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnconnect.Click

Dim addr As Net.IPAddress =
Net.Dns.Resolve(Me.txtIP.Text).AddressList(0)

If Not addr Is Nothing Then
'Create IP endpoint
Dim EP As New Net.IPEndPoint(addr, CInt(Me.txtport.Text))

'create socket
ClientSocket = New
Net.Sockets.Socket(Net.Sockets.AddressFamily.Inter Network,
Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)

'Connect
ClientSocket.BeginConnect(EP, AddressOf ConnectCallBack, Nothing)

End If

End Sub

Private Sub ConnectCallBack(ByVal ar As IAsyncResult)

Try
ClientSocket.EndConnect(ar)

Dim dlg As New NoParamsDelegate(AddressOf ConnectedUI)

Me.Invoke(dlg)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Delegate Sub NoParamsDelegate()

Private Sub ConnectedUI()

Me.rtbinfo.Text += vbNewLine & "Connected" & vbNewLine

Me.btnconnect.Enabled = False
Me.btnsend.Enabled = True
Me.rtbsend.Focus()

End Sub

Private Sub DisconnectedUI()

Me.rtbinfo.Text += vbNewLine & "Disconnected" & vbNewLine

Me.btnconnect.Enabled = True
Me.btnsend.Enabled = False
Me.btnconnect.Focus()

End Sub

Private Sub ReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ClientSocket.EndReceive(ar)

If numbytes = 0 Then
ClientSocket.Shutdown(SocketShutdown.Both)
ClientSocket.Close()

Dim dlg As New NoParamsDelegate(AddressOf DisconnectedUI)

Me.Invoke(dlg)
Else
Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Show in UI
Dim dlg As New OneStringDelegate(AddressOf DisplayReceivedData)
Dim args() As Object = {recv}

Me.Invoke(dlg, args)

'Begin Receive Again
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ReceiveCallBack, bytes)

End If

End Sub

Private Sub DisplayReceivedData(ByVal data As String)

With Me.rtbsend
.SelectionStart = .Text.Length
.SelectedText = data

End With

End Sub

Private Delegate Sub OneStringDelegate(ByVal data As String)

Private Sub btnsend_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnsend.Click

Dim bytes() As Byte = ASCII.GetBytes(Me.txtsend.Text)
ClientSocket.Send(bytes)

End Sub

#End Region

#Region "Listen"

Private Sub btnlisten_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnlisten.Click

Call Listen(homeip, Me.txtlistenport.Text)

End Sub

Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)

ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub

Private Sub ListenCallBack(ByVal ar As IAsyncResult)

Try
ListenSocket.EndAccept(ar)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Sub ListenReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

If numbytes = 0 Then

ListenSocket.Shutdown(SocketShutdown.Both)
ListenSocket.Close()

Else

Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Begin Receive Again
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

End If

End Sub

#End Region

Nov 21 '05 #6

P: n/a

"iwdu15" <iw****@discussions.microsoft.com> сообщил/сообщила в новостях
следующее: news:B2**********************************@microsof t.com...
well that wasnt all my code, that was just relavant to the listening paert, if u want i can show all my code, but homeip is used in the formload event to get the IP address from the computer its running on, and clientsocket wis used to send the connect request in my other code and the code endrecieve is in there, il just list all my code here:


Okay, forget point #1 8=].
But look again at other my suggestions and try to implement them.

Roman
Nov 21 '05 #7

P: n/a
ok, i tried binding the ListenSocket to an endpoint, and it gives an object
reference exception, heres the code, and homeIP and me.txtlistenip.text both
have values in them:

Private Sub btnlisten_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnlisten.Click

Call Listen(homeip, Me.txtlistenport.Text)

End Sub

Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket.Bind(ep)

ListenSocket.Listen(50)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)

ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub
Nov 21 '05 #8

P: n/a
> Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket.Bind(ep)

ListenSocket.Listen(50)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub


Eh, you should first create a socket *before* calling methods on it,
shouldn't you?

ListenSocket = New Socket(...)
ListenSocket.Bind(...)
ListenSocket.Listen(...)
ListenSocket.BeginAccept(...)

Roman
Nov 21 '05 #9

P: n/a
whups, n00b error there, thanks for pointing that out, but now i havbe a
problem. il show the code but one computer says its connected while the other
does not. the computer listening throws an exception saying it cant recieve
data when its not connected while the other computer says its
connected....heres the code, thanks for all your help

Imports System.Net.Sockets
Imports System.Net

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnconnect As System.Windows.Forms.Button
Friend WithEvents txtport As System.Windows.Forms.TextBox
Friend WithEvents txtIP As System.Windows.Forms.TextBox
Friend WithEvents btnlisten As System.Windows.Forms.Button
Friend WithEvents txtlistenport As System.Windows.Forms.TextBox
Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents rtbinfo As System.Windows.Forms.RichTextBox
Friend WithEvents rtbsend As System.Windows.Forms.RichTextBox
Friend WithEvents btnsend As System.Windows.Forms.Button
Friend WithEvents txtsend As System.Windows.Forms.TextBox
Friend WithEvents btndisconnect As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.btnconnect = New System.Windows.Forms.Button
Me.txtport = New System.Windows.Forms.TextBox
Me.txtIP = New System.Windows.Forms.TextBox
Me.btnlisten = New System.Windows.Forms.Button
Me.txtlistenport = New System.Windows.Forms.TextBox
Me.GroupBox1 = New System.Windows.Forms.GroupBox
Me.btndisconnect = New System.Windows.Forms.Button
Me.GroupBox2 = New System.Windows.Forms.GroupBox
Me.rtbinfo = New System.Windows.Forms.RichTextBox
Me.rtbsend = New System.Windows.Forms.RichTextBox
Me.btnsend = New System.Windows.Forms.Button
Me.txtsend = New System.Windows.Forms.TextBox
Me.GroupBox1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
Me.SuspendLayout()
'
'btnconnect
'
Me.btnconnect.Location = New System.Drawing.Point(16, 56)
Me.btnconnect.Name = "btnconnect"
Me.btnconnect.TabIndex = 0
Me.btnconnect.Text = "Connect"
'
'txtport
'
Me.txtport.Location = New System.Drawing.Point(112, 56)
Me.txtport.Name = "txtport"
Me.txtport.Size = New System.Drawing.Size(56, 20)
Me.txtport.TabIndex = 1
Me.txtport.Text = "5190"
'
'txtIP
'
Me.txtIP.Location = New System.Drawing.Point(32, 24)
Me.txtIP.Name = "txtIP"
Me.txtIP.TabIndex = 2
Me.txtIP.Text = "IP"
'
'btnlisten
'
Me.btnlisten.Location = New System.Drawing.Point(24, 48)
Me.btnlisten.Name = "btnlisten"
Me.btnlisten.TabIndex = 3
Me.btnlisten.Text = "Listen"
'
'txtlistenport
'
Me.txtlistenport.Location = New System.Drawing.Point(120, 48)
Me.txtlistenport.Name = "txtlistenport"
Me.txtlistenport.Size = New System.Drawing.Size(56, 20)
Me.txtlistenport.TabIndex = 4
Me.txtlistenport.Text = "5190"
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.txtport)
Me.GroupBox1.Controls.Add(Me.txtIP)
Me.GroupBox1.Controls.Add(Me.btnconnect)
Me.GroupBox1.Controls.Add(Me.btndisconnect)
Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(208, 88)
Me.GroupBox1.TabIndex = 5
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Connect"
'
'btndisconnect
'
Me.btndisconnect.Location = New System.Drawing.Point(16, 56)
Me.btndisconnect.Name = "btndisconnect"
Me.btndisconnect.TabIndex = 9
Me.btndisconnect.Text = "Disconnect"
Me.btndisconnect.Visible = False
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.btnlisten)
Me.GroupBox2.Controls.Add(Me.txtlistenport)
Me.GroupBox2.Location = New System.Drawing.Point(8, 104)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(208, 88)
Me.GroupBox2.TabIndex = 0
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Listen"
'
'rtbinfo
'
Me.rtbinfo.Location = New System.Drawing.Point(16, 200)
Me.rtbinfo.Name = "rtbinfo"
Me.rtbinfo.ReadOnly = True
Me.rtbinfo.Size = New System.Drawing.Size(208, 152)
Me.rtbinfo.TabIndex = 6
Me.rtbinfo.Text = ""
'
'rtbsend
'
Me.rtbsend.Location = New System.Drawing.Point(256, 184)
Me.rtbsend.Name = "rtbsend"
Me.rtbsend.Size = New System.Drawing.Size(296, 168)
Me.rtbsend.TabIndex = 7
Me.rtbsend.Text = ""
'
'btnsend
'
Me.btnsend.Location = New System.Drawing.Point(320, 40)
Me.btnsend.Name = "btnsend"
Me.btnsend.TabIndex = 3
Me.btnsend.Text = "Send"
'
'txtsend
'
Me.txtsend.Location = New System.Drawing.Point(320, 72)
Me.txtsend.Name = "txtsend"
Me.txtsend.TabIndex = 8
Me.txtsend.Text = "TextBox1"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(560, 357)
Me.Controls.Add(Me.txtsend)
Me.Controls.Add(Me.rtbsend)
Me.Controls.Add(Me.GroupBox1)
Me.Controls.Add(Me.GroupBox2)
Me.Controls.Add(Me.rtbinfo)
Me.Controls.Add(Me.btnsend)
Me.Name = "Form1"
Me.Text = "Form1"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox2.ResumeLayout(False)
Me.ResumeLayout(False)

End Sub

#End Region

#Region "Declarations"

Dim homeip As Net.IPAddress
Dim ClientSocket As Net.Sockets.Socket
Dim ASCII As New System.Text.ASCIIEncoding

Dim ListenSocket As Net.Sockets.Socket

#End Region

#Region "Connect"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

homeip =
Net.Dns.GetHostByName(Net.Dns.GetHostName).Address List.GetValue(0)

Me.Text = homeip.ToString

End Sub

Private Sub btnconnect_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnconnect.Click

Dim addr As Net.IPAddress =
Net.Dns.Resolve(Me.txtIP.Text).AddressList(0)

If Not addr Is Nothing Then
'Create IP endpoint
Dim EP As New Net.IPEndPoint(addr, CInt(Me.txtport.Text))

'create socket
ClientSocket = New
Net.Sockets.Socket(Net.Sockets.AddressFamily.Inter Network,
Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)

'Connect
ClientSocket.BeginConnect(EP, AddressOf ConnectCallBack, Nothing)
' ClientSocket.Send(

End If

End Sub

Private Sub ConnectCallBack(ByVal ar As IAsyncResult)

Try
ClientSocket.EndConnect(ar)

Dim dlg As New NoParamsDelegate(AddressOf ConnectedUI)

Me.Invoke(dlg)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Delegate Sub NoParamsDelegate()

Private Sub ConnectedUI()

Me.rtbinfo.Text += vbNewLine & "Connected" & vbNewLine

Me.btnsend.Enabled = True
Me.rtbsend.Focus()

End Sub

Private Sub DisconnectedUI()

Me.rtbinfo.Text += vbNewLine & "Disconnected" & vbNewLine

Me.btnconnect.Visible = True
Me.btndisconnect.Visible = False
Me.btnsend.Enabled = False
Me.btnconnect.Focus()

End Sub

Private Sub ReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ClientSocket.EndReceive(ar)

If numbytes = 0 Then
ClientSocket.Shutdown(SocketShutdown.Both)
ClientSocket.Close()

Dim dlg As New NoParamsDelegate(AddressOf DisconnectedUI)

Me.Invoke(dlg)
Else
Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Show in UI
Dim dlg As New OneStringDelegate(AddressOf DisplayReceivedData)
Dim args() As Object = {recv}

Me.Invoke(dlg, args)

'Begin Receive Again
ClientSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ReceiveCallBack, bytes)

End If

End Sub

Private Delegate Sub OneStringDelegate(ByVal data As String)

Private Sub btnsend_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnsend.Click

Try
If sender Is ClientSocket Then
Dim bytes() As Byte = ASCII.GetBytes(Me.txtsend.Text)
ClientSocket.Send(bytes)
ElseIf sender Is ListenSocket Then
Dim bytes() As Byte = ASCII.GetBytes(Me.txtsend.Text)
ListenSocket.Send(bytes)
End If
Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

#End Region

#Region "Listen"

Private Sub btnlisten_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnlisten.Click

Me.btndisconnect.Visible = True
Me.btnconnect.Visible = False
Call Listen(homeip, Me.txtlistenport.Text)

End Sub

Private Sub Listen(ByVal IP As IPAddress, ByVal port As Integer)

Dim ep As New Net.IPEndPoint(IP, port)

ListenSocket = New Net.Sockets.Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
ListenSocket.Bind(ep)
ListenSocket.Listen(50)
ListenSocket.BeginAccept(AddressOf ListenCallBack, Nothing)

End Sub

Private Sub ListenCallBack(ByVal ar As IAsyncResult)

Try

ListenSocket.EndAccept(ar)

'Begin Receiveing Data
Dim bytes(4095) As Byte
ListenSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

Private Sub ListenReceiveCallBack(ByVal ar As IAsyncResult)

Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

If numbytes = 0 Then

ListenSocket.Shutdown(SocketShutdown.Both)
ListenSocket.Close()

Else

Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Begin Receive Again
ListenSocket.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

End If

End Sub

#End Region
Private Sub DisplayReceivedData(ByVal data As String)

With Me.rtbsend

.SelectionStart = .Text.Length
.SelectedText = data

End With

End Sub

End Class
Nov 21 '05 #10

P: n/a
ok, this is driving me crazy, i get this error on my comp :

A request to send or receive data was disallowed because the socket is not
connected and (when sending on a datagram socket using a sendto call) no
address was supplied

and a false connection state while the other comp has a "true" connection
state and says its connected....wtf is going on!!! lol
Nov 21 '05 #11

P: n/a
Okay, point #1 done. Now let's move on #3 & #4 8=].
It seems that you misunderstand how the listening works.

The Socket.EndAccept() (.Accept()) method returns a *new* socket. This
new socket is *connected* to another computer and is used to
send/receive data. First socket is still *listening* and can be used to
accept new connections; if you don't want them, call it's .Close()
method. You can't call .Receive() on first socket, because it *is not*
connected.

See my pre-pre-previous response, points #3, #4.

Roman
Nov 21 '05 #12

P: n/a
ooohhhhh....that makes so much more sense, so then in order to send data to
the other computer do i create a new socket and just call the "begin send"
method? will the second socket already be connected? thanks for all your help
Nov 21 '05 #13

P: n/a
You dont need to create a new socket...
One was created for you and returned by the ListenSocket.BeginAccept()
method.
eg. (quick & dirty):

dim x as Socket
x = ListenSocket.BeginAccept() ' will assign a new socket to x

You can now use x to send/receive. Your ListenSocket is also still there,
listening away.
Usually for a synchronous server application you put the whole lot in a
continuous loop:

while true

dim x as Socket
x = ListenSocket.Accept() ' will assign a new socket to x

'do stuff with x
x.close()

end while
HTH.
"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:3E**********************************@microsof t.com...
ooohhhhh....that makes so much more sense, so then in order to send data
to
the other computer do i create a new socket and just call the "begin send"
method? will the second socket already be connected? thanks for all your
help

Nov 21 '05 #14

P: n/a
ok that helps alot, thanks, but what about the clientsocket that tried to
connect to the listening socket, does that one create a new socket too?
thanks for your help
Nov 21 '05 #15

P: n/a
no, the connecting socket (usually on another computer, but not necessarily)
uses the same socket that it used to send the connect request.

the only reason a new socket is spawned on the listening machine is to
enable it to send data back to the connecting machine. This is because a
listening socket does just that - it listens. Nothing else.

There is no need for the connecting machine to create a new socket, as it
already has one that it used to send a connect request.
"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:31**********************************@microsof t.com...
ok that helps alot, thanks, but what about the clientsocket that tried to
connect to the listening socket, does that one create a new socket too?
thanks for your help

Nov 21 '05 #16

P: n/a
ok well thank you guys a ton for your help but yet again i have another
question, im getting this error

The IAsyncResult object was not returned from the corresponding asynchronous
method on this class.
on this piece of code for sending and recieveing text:

Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

here is the whole sub

Private Sub ListenReceiveCallBack(ByVal ar As IAsyncResult)

Try
Dim bytes() As Byte = CType(ar.AsyncState, Byte())
Dim numbytes As Int32 = ListenSocket.EndReceive(ar)

If numbytes = 0 Then

ListenSocket.Shutdown(SocketShutdown.Both)
ListenSocket.Close()

Else

Dim recv As String = ASCII.GetString(bytes, 0, numbytes)

Call DisplayReceivedData(recv)

'Clear the buffer
Array.Clear(bytes, 0, bytes.Length)

'Begin Receive Again
connectedListen.BeginReceive(bytes, 0, bytes.Length,
SocketFlags.None, AddressOf ListenReceiveCallBack, bytes)

End If
Catch ex As Exception
Me.rtbinfo.Text += vbNewLine & ex.Message & vbNewLine
End Try

End Sub

thanks for your help guys
Nov 21 '05 #17

P: n/a
OK, it seems that I have to explain each point of my
pre-pre-pre-previous response separately 8=].

You call ListenSocket.EndReceive(), but why? As I already explained,
ListenSocket isn't connected, it's *listening*. You should call the
ClientSocket.EndReceive() here.

Simple logic here: if you call BeginReceive() on ClientSocket you must
call EndReceive() on ClientSocket too, or it's senseless.

Roman
Nov 21 '05 #18

P: n/a
lol sry for all the mixup, i finally got it figured out by fooling around
with the code, i can get it to connect and send and receieve text....thanks
to all you who helped me with this, but being the type of programmer i am, i
want to take it one step further.....how would i go about sending an image or
file accross the connected TCP sockets...would that involve another network
stream (i use one to send text) or what? thanks
Nov 21 '05 #19

P: n/a
you can create another stream if you like - how you program your system is
entirely up to you. there are no limits on what type of data you can send
through a socket, so long as the receiver knows what kind of data it is
receiving. To achieve that, you'd need some kind of simple protocol.

sending files (or any data) larger than about 1400 bytes will require you to
"chop-up" the data into 1400-byte chunks, placing each chunk in a TCP packet
and sending it on its way. You'd usually do that with a while loop:

' open network socket
' open file for reading

while not EndOfFile
' read 1400-byte chunk of file into data buffer
' send data to network stream (use your socket!)
end while

' close file
' close network socket
That is the essence of it.
HTH.

"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:20**********************************@microsof t.com...
lol sry for all the mixup, i finally got it figured out by fooling around
with the code, i can get it to connect and send and receieve
text....thanks
to all you who helped me with this, but being the type of programmer i am,
i
want to take it one step further.....how would i go about sending an image
or
file accross the connected TCP sockets...would that involve another
network
stream (i use one to send text) or what? thanks

Nov 21 '05 #20

P: n/a
hi, when u say "open the file" do u mean using the

System.IO.File.Open(filename)" method?

also how can i get the size of the file?

thanks
--
-iwdu15
Nov 21 '05 #21

P: n/a
the System.IO.StreamReader object is pretty good, and has all the methods
you need:

Dim file1 As New StreamReader("D:\test.txt")
Dim filelen As Long = file1.BaseStream.Length
MsgBox(filelen) ' length of file

dim lineOfText as String

while file1.EndOfStream = False ' are we at the end of file yet?
lineOfText = file1.ReadLine() ' read line of file
end while

file1.close()
For sending chunks of data of a specific size (for network sending), use
ReadBlock() instead of ReadLine().

"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:A2**********************************@microsof t.com...
hi, when u say "open the file" do u mean using the

System.IO.File.Open(filename)" method?

also how can i get the size of the file?

thanks
--
-iwdu15

Nov 21 '05 #22

P: n/a
thanks, that works great for text, but how can i do it for say an image or
file?
Nov 21 '05 #23

P: n/a
in exactly the same way as you did it for text.
The computer does not distinguish between "text" and "image". Its all just
1's and 0's to the machine.

The StreamReader can therefore read any data, and a TCP socket can send any
data.
"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:0B**********************************@microsof t.com...
thanks, that works great for text, but how can i do it for say an image or
file?

Nov 21 '05 #24

This discussion thread is closed

Replies have been disabled for this discussion.