Random error thrown on downloading a file - vb.net

I would really appreciate if someone could help me with this. If I click on the send button, it can't download the log.txt after that...
Imports System
Imports System.IO
Imports System.Collections
Imports System.Security.Principal
Imports System.Runtime.InteropServices
Imports System.Net
Public Class Form1
Public sent As Boolean = False
Private Declare Function SHChangeNotify Lib "Shell32.dll" (ByVal wEventID As Int32, _
ByVal uFlags As Int32, _
ByVal dwitem1 As Int32, _
ByVal deitem2 As Int32) As Int32
Private Sub send_Click(sender As Object, e As EventArgs) Handles send.Click
'If a message has been sent
sent = True
Try
Dim writer As New System.IO.StreamWriter(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt")
sent = False
writer.Write(input.Text)
Try
Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create("ftp://***/c/log.txt"), FtpWebRequest)
ftp.Method = WebRequestMethods.Ftp.DeleteFile
Dim ftpResponse As FtpWebResponse = CType(ftp.GetResponse(), FtpWebResponse)
ftpResponse = ftp.GetResponse()
ftpResponse.Close()
Catch ex As Exception
End Try
My.Computer.Network.UploadFile(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt", New Uri("ftp://***/c/log.txt"), "user", "pass", False, 30000, FileIO.UICancelOption.DoNothing)
input.Text = ""
Catch ex As Exception
End Try
sent = False
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c") Then
My.Computer.FileSystem.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c")
Else
My.Computer.FileSystem.DeleteDirectory(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c", FileIO.DeleteDirectoryOption.DeleteAllContents)
My.Computer.FileSystem.CreateDirectory(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c")
End If
firstcheck()
Threading.Thread.Sleep(500)
End Sub
Private Sub taskbarcheck_Tick(sender As Object, e As EventArgs) Handles taskbarcheck.Tick
If File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop & "\chax.txt") Then
Me.Opacity = 100
Me.Show()
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Desktop & "\chax.txt")
Catch ex As Exception
End Try
Threading.Thread.Sleep(50)
SHChangeNotify(&H8000000, &H1000, 0, 0)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_hide.Click
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Desktop & "\chax.txt")
Catch ex As Exception
End Try
Me.Opacity = 0
Me.Hide()
Threading.Thread.Sleep(50)
SHChangeNotify(&H8000000, &H1000, 0, 0)
End Sub
Private Sub ftpstuff_Tick(sender As Object, e As EventArgs) Handles ftpstuff.Tick
'Try
'delete file if exists
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt")
Catch ex As Exception
End Try
'download file
Try
My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt")
Catch ex As Exception
End Try
'My.Computer.Network.DownloadFile("http://***/c/log.txt", My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt", "", "", False, 30000, False)
Dim myWebClient As New WebClient()
If Not sent = True Then
myWebClient.DownloadFile("http://***/c/log.txt", My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt")
log.Text = File.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt")
End If
End Sub
Private Sub firstcheck()
If Not File.Exists(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt") Then
My.Computer.Network.DownloadFile(New Uri("ftp://***/c/log.txt"), My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\c\log.txt", "user", "pass", False, 30000, True, FileIO.UICancelOption.DoNothing)
End If
End Sub
I tried it every way that i knew of... The "An unhandled exception of type 'System.Net.WebException' occurred in System.dll" is thrown when it tries to download the file after i click the send button.
Thanks for your help in advance!

Yes, it was the stream not closing. Thanks!

If you get an exception before the stream is closed, the code jumps straight to the catch block and the stream is never closed. I presume that the file is locked until the program terminates.
Try adding a command to close the file in the Catch block as well as in your Try block

Related

Auto update issue with drive C:/ in Vb.net

I've created a program with Vb.net that includes an "auto-update" feature. I made it using File A Sync and it seems to work fine, But that's only when I set up the program in any drive except the "C:/" drive, But when I set up the program on the "C:/" drive, The download doesn't start at all. I do not know why. I also tried searching for this issue online but couldn't find any help.
Imports System.IO
Imports System.ComponentModel
Public Class Updater
Dim client As New WebClient
Private Sub Updater_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Downloading_Bar.EditValue = 0
Speed_lb.Visible = True
Speed_lb.Text = " 0 kb/s"
Size_lb.Visible = True
Size_lb.Text = " 0 MB's / 0 MB's"
Try
AddHandler client.DownloadProgressChanged, AddressOf Client_ProgressChanged
AddHandler client.DownloadFileCompleted, AddressOf Client_DownloadCompleted
client.DownloadFileAsync(New Uri(Program_URL), Application.StartupPath & "\Changer NewVersion.exe")
Downloading_Bar.Properties.Step = 1
Downloading_Bar.Properties.PercentView = True
Downloading_Bar.Properties.Maximum = 100
Downloading_Bar.Properties.Minimum = 0
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub Client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
Try
Speed_lb.Text = String.Format("{0} kb/s", (e.BytesReceived / 1024.0).ToString("00"))
Downloading_Bar.EditValue = e.ProgressPercentage.ToString()
Downloading_Bar.PerformStep()
Downloading_Bar.Update()
Size_lb.Text = String.Format("{0} MB's / {1} MB's", (e.BytesReceived / 1024.0 / 1024.0).ToString("0.00"), (e.TotalBytesToReceive / 1024.0 / 1024.0).ToString("0.00"))
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
client.CancelAsync()
client.Dispose()
End Try
End Sub
Private Sub Client_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
If Downloading_Bar.EditValue = 100 Then
Try
My.Computer.FileSystem.RenameFile(Application.StartupPath & "\Changer.exe", "Changer OlderVersion.exe")
My.Computer.FileSystem.RenameFile(Application.StartupPath & "\Changer NewVersion.exe", "Changer.exe")
Process.Start(Application.ExecutablePath)
Process.GetCurrentProcess.Kill()
Me.Dispose()
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub Updater_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
client.CancelAsync()
client.Dispose()
End Sub
End Class

How To Check Network Connectivity From Dll & Pass message to Main form

I want to make dll to check network availability. If Network not available I display message & if the message reply=Retry its check again after 5 seconds. With in the 5 seconds if the network established again exit from the dll & open the main form.
My problem is I cannot display message if the use press cancel to the retry message.
This is my sample code
Main Form
Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
clsConnectionAvailability.CheckNetworkConnectivity()
txtUserName.Text = Environment.UserName
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
This is my dll
Imports System.Windows.Forms
Imports System.Net.NetworkInformation
Public Class clsConnectionAvailability
Private Shared WithEvents WaitTimer As New Timer()
Private Shared intAlarmCounter As Integer = 1
Public Shared Sub CheckNetworkConnectivity(ByRef booExitFlag As Boolean)
' Checking Network Connectivity
If Not NetworkInterface.GetIsNetworkAvailable Then ' If Netowrk Connection Unavailable
clsIsNetworkConnect.CheckNetWorkConnection(booExitFlag) ' Checking Network Connection Is Available or Retry Until Available
MessageBox.Show(CStr(booExitFlag))
End If
End Sub
End Class
Imports System.Windows.Forms
Public Class clsIsNetworkConnect
' Timer Inizialization Variables Declaration
Private Shared WithEvents WaitTimer As New Timer()
Private Shared intAlarmCounter As Integer = 1
Private Shared booExitFlag As Boolean = False
Public Shared Sub CheckNetWorkConnection(ByRef booExitFlag As Boolean)
Try
' Time Event Inizialization
With WaitTimer
.Interval = 5000 ' TimerEventProcessor will Fire after { 5 Seconds }
.Start()
End With
While booExitFlag = False
' After Interval fulfilled, TimerEventProcessor Fired
Application.DoEvents()
End While
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Private Shared Sub TimerEventProcessor(ByVal myObject As Object, ByVal myEventArgs As EventArgs) Handles WaitTimer.Tick
Try
' What to Do When Timer Interval Fulfilled ?
WaitTimer.Stop()
Dim msgConectResult As DialogResult = MessageBox.Show("Network Connectivity Unavailable." & vbCr & _
"Please Inform IT Department." & vbCr & _
"Retry - Check For Network Connectivity Availability Again." & vbCr & _
"Cancel - Exit From The System.", & _
"Network Unavailable", _
MessageBoxButtons.RetryCancel, _
MessageBoxIcon.Information, _
MessageBoxDefaultButton.Button1) ' Display Message & Waiting for Reply
If msgConectResult = DialogResult.Retry Then ' DialogResult = Retry
If Not System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable Then ' If Netowrk Connection Unavailable
intAlarmCounter += 1
WaitTimer.Enabled = True
Else ' If Network Connection Available
booExitFlag = True
End If
Else ' DialogResult = Cancel
booExitFlag = True
Application.Exit()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class
Can anyone please help me to pass cancel message to main form.

SMS Sending Application in VB.net

I'm trying to develop an application with vb.net 2008 to send sms to phone numbers from my pc. I've connected my nokia phone to my pc using USB cable (connected with COM3 port). Given bellow code which I have written should work but message is not being sent and I'm getting my app as deadlock condition:
Imports System
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim ports As String() = SerialPort.GetPortNames
Dim port As String
For Each port In ports
ComboBox1.Items.Add(port)
Next port
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
.Open()
MsgBox("Connected !", MsgBoxStyle.Information)
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
.Write(RichTextBox1.Text & Chr(26))
.Close()
MsgBox("Message Sent!", MsgBoxStyle.Information)
End With
Else
MsgBox("Error on port")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Public Function sendMsg(ByVal port As SerialPort, ByVal PhoneNo As String, ByVal Message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = ExecCommand(port,"AT", 300, "No phone connected")
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.")
Dim command As String = "AT+CMGS=""" & PhoneNo & """"
recievedData = ExecCommand(port,command, 300, "Failed to accept phoneNo")
command = Message & Char.ConvertFromUtf32(26) & vbCr
recievedData = ExecCommand(port,command, 3000, "Failed to send message") '3 seconds
If recievedData.EndsWith(vbCrLf & "OK" & vbCrLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
ExecCommand
Public Function ExecCommand(ByVal port As SerialPort, ByVal command As String, ByVal responseTimeout As Integer, ByVal errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & vbCr)
Dim input As String = ReadResponse(port, responseTimeout)
If (input.Length = 0) OrElse (((Not input.EndsWith(vbCrLf & "> "))) AndAlso ((Not input.EndsWith(vbCrLf & "OK" & vbCrLf)))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
End Try
End Function
You can also try this coding..
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM17")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
Application.DoEvents()
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
Thread.Sleep(500)
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
Thread.Sleep(500)
' SMSPort.WriteLine("AT+CSCA=""+919822078000""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS=" & """" & Form1.TextBox1.Text & """" & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
Thread.Sleep(500)
SMSPort.WriteLine(Form1.TextBox2.Text & Chr(26)) 'SMS sending(specify the labl and the text box)
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
you have to connect your phone with PC Suite or Bluetooth or using USB cable.
After that you have to check the port number and change in coding part according to your port number.
Dim SMSEngine As New SMSCOMMS("COM17")
It is working for me..

Console Application to Winform Application in VB.Net

I have tried this console app and it is a working but when i tried to apply the same codes to create a winform app there is no error but there is no output either.
here is the code:
Console
Imports MT4API
Module Module1
Sub Main()
Try
Dim symbol As String = "EURUSD"
Dim dde As New MT4DDE("fxpro")
AddHandler dde.OnQuote, AddressOf MT_OnQuote
dde.Connect()
dde.Subscribe(symbol)
Console.WriteLine("Press any key...")
Console.ReadKey()
dde.Unubscribe(symbol)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Public Sub MT_OnQuote(ByVal sender As Object, ByVal args As QuoteEventArgs)
Console.WriteLine(args.Symbol & " " & args.Bid & " " & args.Ask)
End Sub
End Module
WinForm
Imports MT4API
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim symbol As String = "EURUSD"
Dim dde As New MT4DDE("cms")
AddHandler dde.OnQuote, AddressOf Me.MT_OnQuote
dde.Connect()
dde.Subscribe(symbol)
TextBox1.AppendText("Press any key...")
dde.Unubscribe(symbol)
Catch ex As Exception
TextBox1.AppendText(ex.Message)
End Try
End Sub
Public Sub MT_OnQuote(ByVal sender As Object, ByVal args As QuoteEventArgs)
Try
'TextBox1.AppendText(args.Symbol)
TextBox1.Text += args.Symbol & vbCrLf
Catch ex As Exception
TextBox1.Text = TextBox1.Text + ex.Message + vbCrLf
End Try
End Sub
End Class
What seems to be the problem? Why the output on the console is not showing in the textbox on the winform.
Thank you very much.

Chat system with one or two ways?

I'm trying con build a simple chat client/software (whole in on executable) wich start listen from the start on the port 5900 and when a client connect to that port the chat is established.
The problem is that only the client can chat to the server, the server cannot answer the client because the connection is working in one way.
The i've tried to connect from "server" to the client when it establishes a connection but the system crash warning me that the port is already on use.
This my code: (working in one way)
Imports System.Net.Sockets
Imports System.Text
Imports System.Reflection
Public Class frmComplete
Dim Data As Integer
Dim Message As String
Private sServer As TcpListener
Private sClient As New TcpClient
Private cServer As TcpListener
Private cClient As New TcpClient
Private cNick As String
Dim BufferSize(1024) As Byte
Private Delegate Sub MessageDelegate(ByVal Message As String)
Private Sub frmComplete_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
srvListen(5900)
btnSend.Enabled = False
End Sub
Private Sub OnServerConnect(ByVal AR As IAsyncResult)
sClient = sServer.EndAcceptTcpClient(AR)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
My.Computer.Audio.Play(Application.StartupPath & "\Connected.wav", AudioPlayMode.Background)
End Sub
Private Sub OnRead(ByVal AR As IAsyncResult)
Data = sClient.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
End Sub
Private Sub PrintMessage(ByVal Message As String)
Try
txtChat.Text = txtChat.Text & Message & vbCrLf
My.Computer.Audio.Play(Application.StartupPath & "\Message.wav", AudioPlayMode.Background)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub srvListen(ByVal port As Integer)
Try
sServer = New TcpListener(System.Net.IPAddress.Any, 5900)
sServer.Start()
'THIS WILL RAISE THE EVENT WHEN A CLIENT IS CONNECTED
sServer.BeginAcceptTcpClient(AddressOf OnServerConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub txtMessage_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMessage.KeyDown
'FIXME (SOUND T_T)
If e.KeyCode = Keys.Enter Then
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
ConnectToServer(txtIP.Text)
cNick = txtNickname.Text
txtNickname.Enabled = False
txtIP.Enabled = False
btnConnect.Enabled = False
End Sub
Private Sub ConnectToServer(ByVal ipadress As String)
Try
cClient.BeginConnect(ipadress, 5900, AddressOf OnClientConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Not String.IsNullOrEmpty(txtMessage.Text) Then
txtChat.Text = txtChat.Text & "Me:" & txtMessage.Text & vbCrLf
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub SendMessage(ByVal message As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(message)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub SendCommand(ByVal command As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(command)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub txtMessage_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMessage.TextChanged
If Not String.IsNullOrEmpty(txtMessage.Text) Then
btnSend.Enabled = True
Else
btnSend.Enabled = False
End If
End Sub
End Class
What I should do? use two ports? one for write and another to read? And if i need to conect multiple clients to one user? (remember the same exe is server/client)
Please help me =(
You aren't reading any data coming back from the Server. You'll notice in your OnServerConnect method you call the BeginRead -- you will also need to do this for your client in the OnClientConnect method, or you'll get a one way communication. Perhaps this is why you are not seeing any data coming through?
I'm guessing, when your Server sends back the data to the client, you aren't getting a hard-error, just no data.
Just glancing over your code I noticed that you have both a TcpClient and TcpListener for your client and server. You don't need this. Your SERVER will be the TcpListener, and your CLIENT will be the TcpClient. By asking if you should connect back on a different port from the server, you are shortchanging yourself of what the TCP connection really is. Once your TcpClient has connected to the TcpServer, your connection is established. There is no need further to attempt to connect.
You're client code should be something similar to:
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientRead(ByVal AR As IAsyncResult)
Data = sServer.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
End Sub