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 23 4348
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
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
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 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
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
"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
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
> 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
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
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
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
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
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
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
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
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
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
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
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
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
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
thanks, that works great for text, but how can i do it for say an image or
file?
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: zZ |
last post by:
Hi All,
I'm building a TCPListener as the server to accept TCPClient connections,
using
TCPListener.AcceptTcpClient.
I'd like to retrieve client's IP after connected, but found no way to do...
|
by: Keith Langer |
last post by:
I have a TCPListener which needs to listen on my LAN IP as well as the
loopback address. In VS.Net 2002 the TCPListener constructor could
accept the port as an argument and it automatically bound...
|
by: ed |
last post by:
Just a warning, I'm somewhat new to .Net.
I'm working on a small TCP/IP server used to xfer files between machines
over a network. Presently I'm using the TcpListener class with the below C++...
|
by: Doug Wyatt |
last post by:
So I'll preface this with the fact that I'm a UNIX developer by training and
have just recently gotten in to C# development on Windows. I'm basically
running in to a problem whereby I suspect...
|
by: Rob White |
last post by:
OK, so I have a TcpListener that is waiting for sockets, this piece of code:
IPAddress localAddress = Dns.GetHostByName(Dns.GetHostName()).AddressList;
IPEndPoint localEP = new...
|
by: Dave Coate |
last post by:
Hi,
I am working on a client-server app. I can get two applications to talk to
each other on the same machine using 127.0.0.1, but as soon as I try it
using a computer name or actual IP address...
|
by: BjЬrn Eliasen |
last post by:
Hi,
I have an application running on all pc's in our company. Basically it is a TCPListener awaiting for sockets to connect and on connection performs the required tasks. The app works fine, but...
|
by: Thos |
last post by:
I have a TcpListener that gets started from a GUI button event
handler:
TcpListener listener;
listener = new TcpListener(IPAddress.Any, 1234);
listener.Start(backLog);
As soon as the third...
|
by: Darwin |
last post by:
Setting a server to listen on 8080 for incoming connections. Written in
VS2005 on a Multi-homed machine.
I get the warning:
Warning 1 'System.Net.Sockets.TcpListener.TcpListener(int)' is obsolete:...
|
by: secutos |
last post by:
When a TcpListener accepts a connection, it returns a TcpClient, which allows you to recieve data. But what about TcpListener.Server.Receive? Does that also allow to receive data in the same way? Or...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |