Console Application to Winform Application in VB.Net - 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.

Related

Deletion of image from folder that is referenced to picture box

sorry i have to rewrite this question as i did not get any update on my same question posted previously.
Below is the code where I'm inserting some data into Ms Access database in visual studio using vb. Net.
When i insert the data i also browse the image for that item and save into the folder that is located under project directory for universal access.
There is a datagridview which displays the data which was inserted to access databas alog with the image in picture box. Whenever the the datagrid view selection is change it display the picure into picture box.
I am having a trouble when i want to delete the data along with image located in project folder as it show the error that 'file used by another process, cant be deleted'
Since i have referenced that image to my picture box, it can not be deleted directly. So here I'm looking for a solution which can display the clone of image in picture box instead of real object.
Below is my code
Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
frmTable.Show()
End Sub
End Class

Debugging error: "Object reference not set to an instance of an object"

Introduction (Warning: Bad English)
Hello everybody. I need some help with my program.
So, basically my program is made for downloading one file and extracting it to known path, for example C:\Users\ProfileName\Documents\Windward. This path is suitable for most part of people. But for some people it's wrong path (Because file need's to be installed in Documents\Windward folder). So i decided to make changeable path. I thought I making everything right, but something gone wrong. And i thing something is frong with this: Dim path As String = TextBox1.Text & "\Localization.zip", but i don't know how to fix it.
Please help me!
Error:
An unhandled exception of type System.InvalidOperationException occurred in AutoDownloadV2.exe
Additional information: Error in form creating. Exception.InnerException. Error: Object reference not set to an instance of an object.
After Debug I recieve this:
in AutoDownloadV2.My.MyProject.MyForms.Create__Instance__[T](T Instance) in :string 190
in AutoDownloadV2.My.MyApplication.OnCreateMainForm() в B:\Projects\Progs\AutoDownloadV2\AutoDownloadV2\AutoDownloadV2\My Project\Application.Designer.vb:string 35
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
in AutoDownloadV2.My.MyApplication.Main(String[] Args) in :string 81 The program '[5452] AutoDownloadV2.exe' has exited with code 0 (0x0).
Here is my code (I have removed the useless part of code.)
Public Class Form1
Public WithEvents download As WebClient
Dim path As String = TextBox1.Text & "\Localization.zip"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Try
My.Computer.FileSystem.DeleteFile(path)
Catch ex As Exception
End Try
download = New WebClient
download.DownloadFileAsync(New Uri("http://http://exsite.example"), path)
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
End Sub
Private Sub download_DownloadProgressChanged(ByVal sender As System.Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles download.DownloadProgressChanged
Try
Label3.Text = "Downloaded : " & e.BytesReceived / 1024 & " kb / " & e.TotalBytesToReceive / 1024 & " kb "
Label4.Text = ProgressBar1.Value & "%"
ProgressBar1.Value = e.ProgressPercentage
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
If e.BytesReceived = e.TotalBytesToReceive Then
Unzip()
End If
End Sub
Public Sub Unzip()
Dim startPath As String = path
Dim zipPath As String = path
Dim extractPath As String = ("C:\Users\" + SystemInformation.UserName + "\Documents\Windward\")
If My.Computer.FileSystem.FileExists(extractPath + "mods\translateMod\Localization.txt") Then
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Localization.txt")
Try
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Version.txt")
Catch e As Exception
End Try
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
Else
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
End If
End Sub
End Class
Move the initialization of path inside the Form1_Load after setting the initial value in TextBox1
Dim path As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
path = TextBox1.Text & "\Localization.zip"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
The problem is caused by the reference to TextBox1 in the global area of your form class. At that point the TextBox1 is still Nothing (not initialized) thus you get the NRE message (Null Reference Exception)

Close form from second form

My first form is login form, when user correctly log in i am hiding login form and showing up second form. Now instead of hiding login form i want to close it from second form. I thought i will be able to do it but somehow i got troubles with it.
So far i did like this below.
I made interface which my FrmLogin implements:
Public Class FrmLogin
Implements ICloseLogin
Interface:
Public Interface ICloseLogin
Sub Close()
End Interface
FrmLogin implementing interface:
Private Sub ICloseLogin_Close() Implements ICloseLogin.Close
Me.Close()
End Sub
Now i am passing FrmLogin (Me) to second form constructor:
Private Sub ShowMainForm()
Dim FrmMain As New FrmMainMDI(Me)
FrmMain.IsMdiContainer = True
FrmMain.StartPosition = FormStartPosition.CenterScreen
FrmMain.Show()
'Me.Hide() 'not anymore
End Sub
Second form:
Public Class FrmMainMDI
Private closeloginfform As ICloseLogin
Sub New(frmlogin As ICloseLogin)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
closeloginfform = frmlogin
End Sub
Private Sub FrmMainMDI_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
closeloginfform.Close()
End Sub
and when i debug and when it comes to line: closeloginfform.Close() i suppose to see only FrmLogin to be closed, but all is closing somehow. Why?
For further discussion:
Imports DataAccessLayer
Imports FormsUtils
Imports BusinessLayer
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Reflection
Imports System.IO
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports Probix
Public Class FrmLogin
Private Property Form As New FormUtils
Private Property DB As New Procs
Private Property _login As String
Private Property _password As String
Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
CheckAccess()
End Sub
Private Sub btnClose_Click(sender As System.Object, e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub FrmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
DB.OpenConn()
If DB.conn.State = ConnectionState.Open Then
Call Form.InitCombo(CboLogin, "SELECT * from tbLogin", DB.conn, "Login", "Login")
Call Form.InitCombo(CboLanguage, "SELECT * from tbLanguage where Active = 1", DB.conn, "Language", "Id")
Lang.name = DirectCast([Enum].Parse(GetType(Lang.LangShortcut), CboLanguage.GetItemText(CboLanguage.SelectedItem)), Lang.LangShortcut)
Else
Logger.LogIt(Modules.FrmLogin.ToString & ": " & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.SqlServerConnectionError_pl), Application.StartupPath & "\log.txt", False)
Application.Exit()
End If
Catch ex As Exception
Logger.LogIt(ex.tostring)
Application.Exit()
Finally
DB.CloseConn()
End Try
End Sub
Private Sub CheckAccess()
Try
_login = CboLogin.SelectedValue
_password = txtPassword.Text
If Not String.IsNullOrEmpty(txtPassword.Text) And Form.WybranoCombo(CboLogin, "Zaznacz login") Then
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("Select COUNT(*) FROM tbLogin WHERE Login = #Login And Password = #Password", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Login", _login)
cmd.Parameters.AddWithValue("#Password", _password)
con.Open()
Dim o As Integer = cmd.ExecuteScalar()
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
End Using
End Using
Else
MsgBox("Write some password !!")
End If
Catch ex As Exception
Logger.LogIt(Modules.FrmLogin.ToString & ":" & Methods.FrmLogin_Load.ToString, WriteMsg.Write(IssueCode.Unknown_pl) & " ------> EX-MESSAGE: " & ex.ToString, Application.StartupPath & " \log.txt", False)
Return
End Try
End Sub
Public Sub taskDialog_Opened(sender As Object, e As EventArgs)
Dim taskDialog As TaskDialog = TryCast(sender, TaskDialog)
taskDialog.Icon = taskDialog.Icon
If Not taskDialog.FooterIcon = TaskDialogStandardIcon.None Then
taskDialog.FooterIcon = taskDialog.FooterIcon
End If
taskDialog.InstructionText = taskDialog.InstructionText
End Sub
End Class
Module Program:
Module Program
Public Sub main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New FrmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
Dim FrmMainMDI As New FrmMainMDI()
Application.Run(FrmMain)
End If
End Sub
End Module
Further discussion 2
Solved???: I've added line within CheckAccess() sub, this line:
Me.DialogResult = DialogResult.OK
so this peace of code has been changed only:
...
'--CREDENTIALS OK
If o > 0 Then
CboLogin.Hide()
txtPassword.Hide()
btnLogin.Hide()
Label1.Hide()
Label2.Hide()
Try
'*************************************
Me.DialogResult = DialogResult.OK '<=========================================
'*************************************
Catch ex As Exception
MsgBox(ex.ToString)
End
End Try
'--CREDENTIALS NOT OK !!
Else
MsgBox("Wrong credentials")
End If
...
A less involved way to do this is to start your app from Sub Main and only start the app if the LogIn is correct. For this:
Add a module to your App, and name it Program. Add a Public Sub Main to it
Go to Project Properties and Uncheck Enable Application Framework
Now, for the Startup Object, select "Sub Main"
You can actually name the module anything, "Program" is descriptive and the convention used in C#. Then the Sub Main code:
Public Sub Main()
Application.EnableVisualStyles()
Dim result As DialogResult
Using frmL As New frmLogin
result = frmL.ShowDialog
End Using
If result = DialogResult.OK Then
frmMain = New MainFrm()
Application.Run(frmMain)
End If
End Sub
Now, your two forms don't even have to know about each other. The MainForm will not even exist if/when the login fails. Whatever overhead there is related to starting/Loading the MainForm is also delayed until (and unless) the log in passes.
Your login button would be something like this (depending on how many failed attempts are allowed):
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
If IsValidUser(tbName.Text, tbPW.Text) Then
DialogResult = Windows.Forms.DialogResult.OK
Else
If tries >= 3 Then
DialogResult = Windows.Forms.DialogResult.Cancel
Else
tries += 1
Exit Sub
End If
End If
Me.Hide()
End Sub

call sub to change USERname color

I want to change USERname color inside RitchTextBox, I am using this code below to call the SUB but all the text now in red?
UPDATE
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & "$ ")
box.SelectionColor = Color.Black
box.AppendText(txtSend)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click
' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text)
Try
If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then
MsgBox("wright a message!", "MsgBox")
Else
client = New TcpClient(txtPCIPadd.Text, 44444)
Dim writer As New StreamWriter(client.GetStream())
txttempmsg.Text = (txtSend.Text)
writer.Write(txtUsername.Text + " # " + txtSend.Text)
AddMessage(txtUsername.Text, txttempmsg.Text + vbCrLf)
'txtmsg.Text="You:" + txtmessage.Text)
writer.Flush()
txtSend.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
When you have a problem trying to get something to work in your program. It is easier to create a test example that you can then use to figure out what is happening without dealing with a lot of other variables in your larger program. In your case I created a VB Winforms app, added a RichTextBox, two TextBox's and a Button. By doing so I am able to show that the function is working.
Public Class Form1
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & " :") 'Note added colon
box.SelectionColor = Color.Black
box.AppendText(txtSend) 'Note changed variable name to parameter name
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddMessage(txtUsername.Text, txttempmsg.Text)
End Sub
End Class
Example:

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