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

simple connect

P: n/a
hey, i was wondering if 1) anyone could tell me whats wrong with my code, i
did a little fixing to the msdn version fo this, or 2) how to make a simple
program that will connect and listen for connections async. if the user
pushes the selected buttons.
i just want a program that connects to another computer on the port and IP
address selected and if the other computer is listening, then connect to it
but this code doesnt work :

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Net.DnsPermissionAttribute
Imports System.Security.Permissions

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 GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents btnconnect As System.Windows.Forms.Button
Friend WithEvents txtconnectport As System.Windows.Forms.TextBox
Friend WithEvents txtconnectIP As System.Windows.Forms.TextBox
Friend WithEvents rtbconnect As System.Windows.Forms.RichTextBox
Friend WithEvents btnlisten As System.Windows.Forms.Button
Friend WithEvents rtblisten As System.Windows.Forms.RichTextBox
Friend WithEvents txtlistenport As System.Windows.Forms.TextBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.GroupBox1 = New System.Windows.Forms.GroupBox
Me.txtconnectport = New System.Windows.Forms.TextBox
Me.txtconnectIP = New System.Windows.Forms.TextBox
Me.btnconnect = New System.Windows.Forms.Button
Me.GroupBox2 = New System.Windows.Forms.GroupBox
Me.btnlisten = New System.Windows.Forms.Button
Me.txtlistenport = New System.Windows.Forms.TextBox
Me.rtbconnect = New System.Windows.Forms.RichTextBox
Me.rtblisten = New System.Windows.Forms.RichTextBox
Me.GroupBox1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
Me.SuspendLayout()
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.txtconnectport)
Me.GroupBox1.Controls.Add(Me.txtconnectIP)
Me.GroupBox1.Controls.Add(Me.btnconnect)
Me.GroupBox1.Controls.Add(Me.rtbconnect)
Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(616, 176)
Me.GroupBox1.TabIndex = 0
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Connect"
'
'txtconnectport
'
Me.txtconnectport.Location = New System.Drawing.Point(128, 72)
Me.txtconnectport.MaxLength = 5
Me.txtconnectport.Name = "txtconnectport"
Me.txtconnectport.Size = New System.Drawing.Size(56, 20)
Me.txtconnectport.TabIndex = 1
Me.txtconnectport.Text = "Port"
'
'txtconnectIP
'
Me.txtconnectIP.Location = New System.Drawing.Point(128, 32)
Me.txtconnectIP.Name = "txtconnectIP"
Me.txtconnectIP.TabIndex = 2
Me.txtconnectIP.Text = "IP"
'
'btnconnect
'
Me.btnconnect.Location = New System.Drawing.Point(32, 56)
Me.btnconnect.Name = "btnconnect"
Me.btnconnect.TabIndex = 0
Me.btnconnect.Text = "Connect"
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.btnlisten)
Me.GroupBox2.Controls.Add(Me.txtlistenport)
Me.GroupBox2.Controls.Add(Me.rtblisten)
Me.GroupBox2.Location = New System.Drawing.Point(8, 192)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(616, 160)
Me.GroupBox2.TabIndex = 0
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Listen"
'
'btnlisten
'
Me.btnlisten.Location = New System.Drawing.Point(56, 80)
Me.btnlisten.Name = "btnlisten"
Me.btnlisten.TabIndex = 4
Me.btnlisten.Text = "Listen"
'
'txtlistenport
'
Me.txtlistenport.Location = New System.Drawing.Point(168, 80)
Me.txtlistenport.MaxLength = 5
Me.txtlistenport.Name = "txtlistenport"
Me.txtlistenport.Size = New System.Drawing.Size(56, 20)
Me.txtlistenport.TabIndex = 3
Me.txtlistenport.Text = "Port"
'
'rtbconnect
'
Me.rtbconnect.Location = New System.Drawing.Point(296, 16)
Me.rtbconnect.Name = "rtbconnect"
Me.rtbconnect.Size = New System.Drawing.Size(312, 152)
Me.rtbconnect.TabIndex = 3
Me.rtbconnect.Text = ""
'
'rtblisten
'
Me.rtblisten.Location = New System.Drawing.Point(296, 16)
Me.rtblisten.Name = "rtblisten"
Me.rtblisten.Size = New System.Drawing.Size(312, 136)
Me.rtblisten.TabIndex = 4
Me.rtblisten.Text = ""
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(632, 358)
Me.Controls.Add(Me.GroupBox1)
Me.Controls.Add(Me.GroupBox2)
Me.Name = "Form1"
Me.Text = "Form1"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox2.ResumeLayout(False)
Me.ResumeLayout(False)

End Sub

#End Region

Dim HomeIP As IPAddress

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

HomeIP = Dns.GetHostByName(Dns.GetHostName).AddressList.Get Value(0)
Me.Text = HomeIP.ToString

End Sub

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

Call Connect()

End Sub

Private Sub Connect()

Try
Dim tcpClient As New System.Net.Sockets.TcpClient

'"Localhost" string is used when the client and the listener are
on the same computer.
'If the listener is listening at a computer that is different
from the client, provide the host name of the computer
'where the listener is listening.
tcpClient.Connect(Me.txtconnectIP.Text, Me.txtconnectport.Text)

Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is
anybody listening...")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
'****Dim bytes(tcpClient.ReceiveBufferSize) As Byte
'''****networkStream.Read(bytes, 0,
CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
'****Dim returndata As String =
Encoding.ASCII.GetString(bytes)
'****Console.WriteLine(("TCP Server returned: " + returndata))
Else
If Not networkStream.CanRead Then
Me.rtbconnect.Text += "Could not write data to data
stream"
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Me.rtbconnect.Text += "Could not read data from data
stream"
tcpClient.Close()
End If
End If
End If
' Pause to let the user view the console output.
'**** Console.ReadLine()
Catch ex As Exception
Me.rtbconnect.Text += ex.Message
End Try

End Sub

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

Call CTestTCPServer()

End Sub

<DnsPermissionAttribute(SecurityAction.Demand, Unrestricted:=True)>
Private Sub CTestTCPServer()

'Listening must be on the same port that the client is connected on.
Dim portNumber As Integer = Me.txtlistenport.Text

'"Localhost" string is used when the client and the listener are on
the same computer.
'If the listener is listening at a computer that is different from
the client, then provide the host name of the computer
'where the listener is listening.
'****Dim tcpListener As New
TcpListener(CType(Dns.Resolve("Localhost").Address List(0), IPAddress),
portNumber)
'Comment the previous line and uncomment the following line if you
are using Visual Basic .NET (2003).
Dim tcpListener As New TcpListener(HomeIP, portNumber)

tcpListener.Start()

Me.rtblisten.Text += "TCP Server is up and waiting for Client
connection..."

Try
''Accept the pending client connection and return a TcpClient
for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Me.rtblisten.Text += "Connection accepted."
' Get the data stream.
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Read the data stream into a byte array.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes)
Me.rtblisten.Text += "Client sent: " + clientdata
Dim responseString As String = "Successfully connected to TCP
server."
Dim sendBytes As [Byte]() =
Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Me.rtblisten.Text += "Message Sent by TCP Server /> : " +
responseString
'Close TcpListener and TcpClient.
tcpClient.Close()
tcpListener.Stop()
Catch ex As Exception
Me.rtblisten.Text += ex.Message
End Try

End Sub

End Class
Nov 21 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"iwdu15" <iw****@discussions.microsoft.com> wrote in message
news:71**********************************@microsof t.com...
hey, i was wondering if 1) anyone could tell me whats wrong with my code, i did a little fixing to the msdn version fo this, or 2) how to make a simple program that will connect and listen for connections async. if the user
pushes the selected buttons.
i just want a program that connects to another computer on the port and IP
address selected and if the other computer is listening, then connect to it but this code doesnt work :

Hi iwdu15,

1. I made some adjustments so the code does what you want.
2. I'm not an expert but the next thing I would do is put the network stuff
in a separate thread so it won't block the user interface.

Christiaan.


Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Net.DnsPermissionAttribute
Imports System.Security.Permissions

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 GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents txtListenPort As System.Windows.Forms.TextBox
Friend WithEvents rtbListen As System.Windows.Forms.RichTextBox
Friend WithEvents rtbConnect As System.Windows.Forms.RichTextBox
Friend WithEvents txtConnectIp As System.Windows.Forms.TextBox
Friend WithEvents txtConnectPort As System.Windows.Forms.TextBox
Friend WithEvents btnConnect As System.Windows.Forms.Button
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents btnListen As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.GroupBox1 = New System.Windows.Forms.GroupBox()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label1 = New System.Windows.Forms.Label()
Me.rtbConnect = New System.Windows.Forms.RichTextBox()
Me.txtConnectIp = New System.Windows.Forms.TextBox()
Me.txtConnectPort = New System.Windows.Forms.TextBox()
Me.btnConnect = New System.Windows.Forms.Button()
Me.GroupBox2 = New System.Windows.Forms.GroupBox()
Me.Label3 = New System.Windows.Forms.Label()
Me.txtListenPort = New System.Windows.Forms.TextBox()
Me.rtbListen = New System.Windows.Forms.RichTextBox()
Me.btnListen = New System.Windows.Forms.Button()
Me.Button1 = New System.Windows.Forms.Button()
Me.GroupBox1.SuspendLayout()
Me.GroupBox2.SuspendLayout()
Me.SuspendLayout()
'
'GroupBox1
'
Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control()
{Me.Label2, Me.Label1, Me.rtbConnect, Me.txtConnectIp, Me.txtConnectPort,
Me.btnConnect})
Me.GroupBox1.Location = New System.Drawing.Point(24, 24)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(528, 152)
Me.GroupBox1.TabIndex = 0
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Connect"
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(16, 64)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(48, 23)
Me.Label2.TabIndex = 11
Me.Label2.Text = "Port"
'
'Label1
'
Me.Label1.Location = New System.Drawing.Point(16, 32)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(56, 23)
Me.Label1.TabIndex = 10
Me.Label1.Text = "IP"
'
'rtbConnect
'
Me.rtbConnect.Location = New System.Drawing.Point(216, 24)
Me.rtbConnect.Name = "rtbConnect"
Me.rtbConnect.Size = New System.Drawing.Size(280, 104)
Me.rtbConnect.TabIndex = 9
Me.rtbConnect.Text = ""
'
'txtConnectIp
'
Me.txtConnectIp.Location = New System.Drawing.Point(72, 32)
Me.txtConnectIp.Name = "txtConnectIp"
Me.txtConnectIp.TabIndex = 8
Me.txtConnectIp.Text = "127.0.0.1"
'
'txtConnectPort
'
Me.txtConnectPort.Location = New System.Drawing.Point(72, 56)
Me.txtConnectPort.Name = "txtConnectPort"
Me.txtConnectPort.TabIndex = 7
Me.txtConnectPort.Text = "12345"
'
'btnConnect
'
Me.btnConnect.Location = New System.Drawing.Point(48, 104)
Me.btnConnect.Name = "btnConnect"
Me.btnConnect.TabIndex = 6
Me.btnConnect.Text = "Connect"
'
'GroupBox2
'
Me.GroupBox2.Controls.AddRange(New System.Windows.Forms.Control()
{Me.Label3, Me.txtListenPort, Me.rtbListen, Me.btnListen})
Me.GroupBox2.Location = New System.Drawing.Point(24, 200)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(528, 168)
Me.GroupBox2.TabIndex = 1
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Listen"
'
'Label3
'
Me.Label3.Location = New System.Drawing.Point(24, 40)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(32, 16)
Me.Label3.TabIndex = 12
Me.Label3.Text = "Port"
'
'txtListenPort
'
Me.txtListenPort.Location = New System.Drawing.Point(72, 32)
Me.txtListenPort.Name = "txtListenPort"
Me.txtListenPort.TabIndex = 11
Me.txtListenPort.Text = "12345"
'
'rtbListen
'
Me.rtbListen.Location = New System.Drawing.Point(216, 24)
Me.rtbListen.Name = "rtbListen"
Me.rtbListen.Size = New System.Drawing.Size(280, 112)
Me.rtbListen.TabIndex = 10
Me.rtbListen.Text = ""
'
'btnListen
'
Me.btnListen.Location = New System.Drawing.Point(80, 80)
Me.btnListen.Name = "btnListen"
Me.btnListen.TabIndex = 10
Me.btnListen.Text = "Listen"
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(512, 376)
Me.Button1.Name = "Button1"
Me.Button1.TabIndex = 2
Me.Button1.Text = "Test"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(592, 397)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Button1,
Me.GroupBox2, Me.GroupBox1})
Me.Name = "Form1"
Me.Text = "Form1"
Me.GroupBox1.ResumeLayout(False)
Me.GroupBox2.ResumeLayout(False)
Me.ResumeLayout(False)

End Sub

#End Region

Dim HomeIP As IPAddress

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
HomeIP = Dns.GetHostByName(Dns.GetHostName).AddressList.Get Value(0)
Me.Text = HomeIP.ToString
txtConnectIp.Text = HomeIP.ToString
End Sub

Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnConnect.Click
Call Connect()
End Sub

Private Sub Connect()
Try
Dim tcpClient As New System.Net.Sockets.TcpClient()

'"Localhost" string is used when the client and the listener are
on the same computer.
'If the listener is listening at a computer that is different
from the client, provide the host name of the computer
'where the listener is listening.
tcpClient.Connect(Me.txtConnectIp.Text, Me.txtConnectPort.Text)

Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is
anybody listening...")
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
Dim noOfBytesRead As Integer 'I ADDED THIS VARIABLE
noOfBytesRead = networkStream.Read(bytes, 0,
CInt(tcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes,
0, noOfBytesRead)
rtbConnect.Text += "TCP Server returned: " + returndata +
vbNewLine
Else
If Not networkStream.CanRead Then
Me.rtbConnect.Text += "Could not write data to data
stream" + vbNewLine
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
Me.rtbConnect.Text += "Could not read data from data
stream" + vbNewLine
tcpClient.Close()
End If
End If
End If
' Pause to let the user view the console output.
'**** Console.ReadLine()
Catch ex As Exception
Me.rtbConnect.Text += ex.Message + vbNewLine
End Try

End Sub

Private Sub btnListen_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnListen.Click
Call CTestTCPServer()
End Sub

<DnsPermissionAttribute(SecurityAction.Demand, Unrestricted:=True)>
Private Sub CTestTCPServer()

'Listening must be on the same port that the client is connected on.
Dim portNumber As Integer = Me.txtListenPort.Text

'"Localhost" string is used when the client and the listener are on
the same computer.
'If the listener is listening at a computer that is different from
the client,
'then provide the host name of the computer where the listener is
listening.
'****Dim tcpListener As New
TcpListener(CType(Dns.Resolve("Localhost").Address List(0), IPAddress),
portNumber)
'Comment the previous line and uncomment the following line if you
are using Visual Basic .NET (2003).
Dim tcpListener As New TcpListener(HomeIP, portNumber)
tcpListener.Start()

Me.rtbListen.Text += "TCP Server is up and waiting for client
connection..." + vbNewLine
Me.rtbListen.Update() 'I ADDED THIS LINE

Try
''Accept the pending client connection and return a TcpClient
for communication.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
Me.rtbListen.Text += "Connection accepted." + vbNewLine
Me.rtbListen.Update() 'I ADDED THIS LINE
' Get the data stream.
Dim networkStream As NetworkStream = tcpClient.GetStream()
' Read the data stream into a byte array.
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
Dim noOfBytesRead As Integer 'I ADDED THIS VARIABLE
noOfBytesRead = networkStream.Read(bytes, 0,
CInt(tcpClient.ReceiveBufferSize))
' Return the data received from the client to the console.
Dim clientdata As String = Encoding.ASCII.GetString(bytes, 0,
noOfBytesRead)
Me.rtbListen.Text += "Client sent: " + clientdata + vbNewLine
Dim responseString As String = "Successfully connected to TCP
server."
Dim sendBytes As [Byte]() =
Encoding.ASCII.GetBytes(responseString)
networkStream.Write(sendBytes, 0, sendBytes.Length)
Me.rtbListen.Text += "Message Sent by TCP Server /> : " +
responseString + vbNewLine
'Close TcpListener and TcpClient.
networkStream.Close() 'I ADDED THIS LINE
tcpClient.Close()
Catch ex As Exception
Me.rtbListen.Text += ex.Message
End Try
tcpListener.Stop()

End Sub
End Class

Nov 21 '05 #2

P: n/a
See

http://www.codeproject.com/csharp/socketsincs.asp

for

Asynchronous socket communication
By John McTainsh

An article on using sockets to communicate in a non-blocking manner. The
sample works through building a simple chat client and server.

(in C#.)
Nov 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.