No UDP packets received using async method VB.Net - vb.net

I'm trying to send a picture over lan using UDP. I have to "cut" the picture into small packets and then reassemble it at the other end. So far I've made the server and almost the client (the server sends the picture). I've made some tests with BeginReceive and worked (on other project). Now I get nothing on the client(no error..nothing). Here's the code for the server:
Imports System
Imports System.IO
Imports System.Net
Imports System.Threading
Imports System.Net.Sockets
Imports System.Text.Encoding
Public Class Form1
Dim publisher As New Sockets.UdpClient(0)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sendbytes() As Byte = ASCII.GetBytes(txt1.Text)
Dim img As Image, img_stream As MemoryStream, buffer As Byte()
Dim packet_size As Integer = 1500, sent_size As Long
Try
publisher.Connect("localhost", 60000)
img_stream = imgToBytes(txt1.Text)
ReDim buffer(packet_size)
While Not img_stream.Position = img_stream.Length
sent_size += img_stream.Read(buffer, 0, packet_size)
publisher.Send(buffer, buffer.Length)
End While
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
Function imgToBytes(ByVal file_name As String) As MemoryStream
Dim img As Image = Image.FromFile(file_name)
Dim stream As New MemoryStream
img.Save(stream, Drawing.Imaging.ImageFormat.Jpeg)
stream.Position = 0
Return stream
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Form2.Show()
End Sub
End Class
The client is on the second form:
Imports System
Imports System.IO
Imports System.Net
Imports System.Threading
Imports System.Net.Sockets
Imports System.Text.Encoding
Public Class Form2
Dim ep As IPEndPoint = New IPEndPoint(IPAddress.Any, 0)
Dim client As New UdpClient(1000)
Public Event new_msg(ByVal msg As Byte())
Public Sub client_msg(ByVal msg As Byte())
Debug.Print("a")
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try ''don't know why I put this here
client.BeginReceive(New AsyncCallback(AddressOf receive), client)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
Sub receive(ByVal ar As IAsyncResult)
Dim buffer As Byte()
Debug.Print("b")
Try
buffer = client.EndReceive(ar, ep)
''RaiseEvent new_msg(buffer)
client.BeginReceive(New AsyncCallback(AddressOf receive), client)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
End Class
Where is the problem?

Your problem is that your clients are not communicating over the same port.
In Form2 you do:
Dim client As New UdpClient(1000)
Then in Form1 when you connect you do:
publisher.Connect("localhost", 60000)
Change the port to 1000 and it works:
publisher.Connect("localhost", 1000)

Related

How to add a chrome web browser control to my application in visual basic

i want to add a google chrome control to my application because internet explorer control isnt very good.It shows the web pages wrong etc.Some help please
if you want replace internet explorer with chrome in your winforms you must have to include third party tool (library). now a days there many some of that are
1] Selenium
2] CefSharp
3] DotNet Browser
4] OpenWebKitSharp
given list are only some browser . you could also google it out "winform replace webbrowser with chrome".
Thanks
my friend please refere to code given below.
Imports Microsoft.Win32
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms
Imports mshtml
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Drawing.Imaging
Imports OpenQA.Selenium.Chrome.ChromeDriver
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Interactions
Imports OpenQA.Selenium.Interactions.Actions
Imports OpenQA.Selenium.Support.UI
Imports OpenQA.Selenium.Chrome
Imports OpenQA.Selenium.Support.Events
Imports System.Text.RegularExpressions
Public Class CLOGIN
Public MASTERID As String = ""
Public MASTERPASSWORD As String = ""
Dim webbrowse As New WebBrowser()
Private _DOCUMENTREADY As Integer
Private ERRORSFOUND As Boolean
Private RequestID As String
Private READYSTATE As Boolean
Public mconfig As New MasterConfig()
Public GSTCAPTCHA As New CommonCaptcha()
Private CaptchaCookie = ""
Private WEBSTATEINC As Boolean = True
Public wbr As New Chrome.ChromeDriver(mconfig.MASTERSERVICE, mconfig.MASTEROPTION)
Public WithEvents driver As New EventFiringWebDriver(wbr)
Private Sub CLOGIN_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler driver.Navigated, AddressOf OnNavigated
RECALL()
End Sub
Public Function CropImage(ByVal source As Bitmap, ByVal section As Rectangle) As Bitmap
Dim bmp As New Bitmap(section.Width, section.Height)
Dim g As Graphics = Graphics.FromImage(bmp)
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel)
Return bmp
End Function
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End Sub
Public Sub RECALL()
INITLABEL:
wbr.Url = "https://example.com/services/do_login"
wbr.Navigate()
System.Threading.Thread.Sleep(2500)
Application.DoEvents()
If Not wbr.Url.Contains("/do_login") Then
GoTo INITLABEL
End If
Dim origialheight = Me.MdiParent.Height
Dim dblheight = origialheight * 0.75
Dim proportedration = origialheight - dblheight
Dim maxwidth = Me.MdiParent.Width
Me.MdiParent.WindowState = FormWindowState.Normal
Me.MdiParent.Location = New Point(0, dblheight + 1)
Me.MdiParent.Size = New Size(maxwidth, proportedration) 'dblheight
wbr.Manage().Window().Size = New System.Drawing.Size(maxwidth, dblheight) 'dblheight
wbr.Manage().Window().Position = New Point(0, 0)
Dim action As New Actions(wbr)
Dim wait As New WebDriverWait(wbr, System.TimeSpan.FromSeconds(5))
wait.Until(ExpectedConditions.ElementExists(By.Id("username")))
wbr.FindElement(By.XPath("//*[#id='username']")).SendKeys(MASTERID) 'txtuserid.Text
wbr.FindElement(By.XPath("//*[#id='user_pass']")).SendKeys(MASTERPASSWORD)
Threading.Thread.Sleep(3000)
Application.DoEvents()
Dim master = ""
wbr.FindElement(By.XPath("//*[#id='captcha']")).SendKeys(OpenQA.Selenium.Keys.Tab)
End Sub
Private Sub btnlogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogout.Click
End Sub
Private Sub lblshowpass_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblshowpass.CheckedChanged
If lblshowpass.Checked Then
txtpassword.PasswordChar = ""
Else
txtpassword.PasswordChar = "*"
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, Button5.Click
wbr.FindElement(By.XPath("//*[#id='captcha']")).SendKeys(TextBox2.Text)
wbr.FindElement(By.XPath("//*[#type='submit']")).Submit()
WaitUntilDocumentIsReady(TimeSpan.FromSeconds(5))
System.Threading.Thread.Sleep(1500)
Application.DoEvents()
If wbr.Url.Contains("/login") Then
Dim wait As New WebDriverWait(wbr, System.TimeSpan.FromSeconds(3)) 'you can play with the time integer to wait for longer than 15 seconds.`
Try
Dim myLink = wbr.FindElementByXPath("//*[#data-ng-if='loginform.captcha.$error.invalid_captcha']")
If Not myLink Is Nothing Then 'wbr.PageSource.Contains("Enter valid Letters shown") Then
MsgBox("Invalid Captcha Code", MsgBoxStyle.Critical, "Application Error")
wbr.FindElement(By.XPath("//*[#id='user_pass']")).SendKeys(txtpassword.Text)
Me.TextBox1.Text = ""
Me.TextBox1.Focus()
End If
Catch ex As Exception
End Try
Try
If wbr.PageSource.Contains("class=""alert alert-danger""") Then
MsgBox("Invalid User ID or Password", MsgBoxStyle.Critical, "Application Error")
wbr.Dispose()
Application.Exit()
End If
Catch ex As Exception
End Try
Else
wbr.Manage().Window().Maximize()
Me.MdiParent.WindowState = FormWindowState.Minimized
End If
End Sub
Public Sub ReCaptcha(ByVal wbr As ChromeDriver)
End Sub
Public Sub OnNavigated(ByVal sender As Object, ByVal e As Support.Events.WebDriverNavigationEventArgs) Handles driver.Navigated
If wbr.Url.Contains("/do_login") Then
Dim wait As New WebDriverWait(wbr, System.TimeSpan.FromSeconds(3))
Try
Dim myLink = wbr.FindElementByXPath("//*[#data-ng-if='loginform.captcha.$error.invalid_captcha']")
If Not myLink Is Nothing Then 'wbr.PageSource.Contains("Enter valid Letters shown") Then
MsgBox("Invalid Captcha Code", MsgBoxStyle.Critical, "Application Error")
wbr.FindElement(By.XPath("//*[#id='user_pass']")).SendKeys(txtpassword.Text)
Me.TextBox1.Text = ""
Me.TextBox1.Focus()
End If
Catch ex As Exception
End Try
Try
If wbr.PageSource.Contains("class=""alert alert-danger""") Then
MsgBox("Invalid User ID or Password", MsgBoxStyle.Critical, "Application Error")
wbr.Dispose()
Application.Exit()
End If
Catch ex As Exception
End Try
Else
End If
End Sub
Public Sub truncateUnfinish(ByVal string1 As String)
If Not IsNumeric(string1) Then
Return
End If
Dim answer = Regex.Replace(string1, "\D", "")
If string1.Length > 6 Then
TextBox2.Text = answer.Substring(0, 6)
End If
End Sub
Function AllCaps(ByVal stringToCheck As String) As Boolean
AllCaps = StrComp(stringToCheck, UCase(stringToCheck), vbBinaryCompare) = 0
End Function
End Class
Thanks.

Server client application vb.net

I try to make a server client application server client separated
and the client code it seems have no error but on the server i get an error but i don t get it work
its come this error
Error 1 Handles clause requires a WithEvents variable defined in the containing type or one of its base types. c:\users\monchique discovery\documents\visual studio 2012\Projects\serverxpto\serverxpto\frmServer.vb 36 120 serverxpto
this is my server code
Imports System.Net, System.Net.Sockets
Public Class frmServer
Dim serverSocket As Socket
Dim clientSocket As Socket
Private Sub frmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 8800)
serverSocket.Bind(IpEndPoint)
serverSocket.Listen(5)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
End Sub
Private Sub OnAccept(ByVal ar As IAsyncResult)
clientSocket = serverSocket.EndAccept(ar)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
AddClient(clientSocket)
End Sub
Delegate Sub _AddClient(ByVal client As Socket)
Private Sub AddClient(ByVal client As Socket)
If InvokeRequired Then
Invoke(New _AddClient(AddressOf AddClient), client)
Exit Sub
End If
Dim lvi As New ListViewItem(client.LocalEndPoint.ToString)
lvi.Tag = client
lsvClients.Items.Add(lvi)
End Sub
Private Sub Send(ByVal msg As String, ByVal client As Socket)
Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(msg)
client.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), client)
End Sub
Private Sub OnSend(ByVal ar As IAsyncResult)
Dim client As Socket = ar.AsyncState
client.EndSend(ar)
End Sub
Private Sub SendMessageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendMessageToolStripMenuItem.Click
Send("Message from server", lsvClients.SelectedItems(0).Tag)
End Sub
End Class

Tcp Connection only reads one message

I am trying to create a simple Game which needs a TcpConnection.
So I created a Server class which wraps the TcpListener, same goes with Client and TcpClient. But when I attach my Listener Sub and send Messages it only gets called on the first one:
Server
Imports System.Net.Sockets
Public Class Server
Inherits ConnectionPartner
Private Server As TcpListener
Private Client As TcpClient
Private Stream As NetworkStream
Private Port As Integer
Public Sub Init(ByVal port As Integer)
Server = New TcpListener(port)
End Sub
Public Sub Open()
Server.Start()
Client = Server.AcceptTcpClient()
Stream = Client.GetStream()
End Sub
Public Overrides Sub Write(ByVal Message As String)
Dim Bytes() As Byte = Encoder.GetBytes(Message)
Me.Write(Bytes)
End Sub
Public Overrides Sub Write(ByVal Message() As Byte)
If Stream Is Nothing Then Return
Stream.Write(Message, 0, Message.Length)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
Listen(Sub(ByVal Message() As Byte)
Handler(Encoder.GetString(Message))
End Sub)
End Sub
Public Overrides Sub Listen(ByRef Handler As Action(Of Byte()))
Dim Buffer(Client.ReceiveBufferSize()) As Byte
While (True)
Utils.Log("Listening")
Client.GetStream().Read(Buffer, 0, Buffer.Length)
Handler(Buffer)
End While
End Sub
Public Sub Close()
Try
Client.Close()
Catch ex As Exception
End Try
Try
Server.Stop()
Catch ex As Exception
End Try
End Sub
End Class
Client
Imports System.Net
Imports System.Net.Sockets
Public Class Client
Inherits ConnectionPartner
Private Socket As TcpClient
Private Stream As NetworkStream
Private Port As Integer
Public Sub Init()
Socket = New TcpClient()
End Sub
Public Sub Open(ByVal Ip As IPAddress, ByVal Port As Integer)
Socket.Connect(Ip, Port)
Stream = Socket.GetStream()
End Sub
Public Overrides Sub Write(ByVal Message As String)
Dim Bytes() As Byte = Encoder.GetBytes(Message)
Me.Write(Bytes)
End Sub
Public Overrides Sub Write(ByVal Message() As Byte)
If Stream Is Nothing Then Return
Stream.Write(Message, 0, Message.Length)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
Listen(Sub(ByVal Message() As Byte)
Handler(Encoder.GetString(Message))
End Sub)
End Sub
Public Overrides Sub Listen(ByRef Handler As Action(Of Byte()))
Dim Buffer(Socket.ReceiveBufferSize()) As Byte
While (True)
Utils.Log("Listening")
Stream.Read(Buffer, 0, Buffer.Length)
Handler(Buffer)
End While
End Sub
Public Sub Close()
Try
Socket.Close()
Catch ex As Exception
End Try
End Sub
End Class
My Test Class
Imports System.Net
Imports System.Threading
Class MainWindow
Private Server As Server = New Server()
Private Client As Client = New Client()
Private C As Connection
Private Port As Integer = My.Resources.Port
Private Sub button_client_init_Click(sender As Object, e As RoutedEventArgs) Handles button_client_init.Click
Client.Init()
End Sub
Private Sub button_client_start_Click(sender As Object, e As RoutedEventArgs) Handles button_client_start.Click
Client.Open(Dns.GetHostEntry("localhost").AddressList(1), Port)
End Sub
Private Sub button_client_write_Click(sender As Object, e As RoutedEventArgs) Handles button_client_write.Click
Client.Write("bar")
End Sub
Private Sub button_client_listen_Click(sender As Object, e As RoutedEventArgs) Handles button_client_listen.Click
Dim T As Thread = New Thread(Sub()
Client.Listen(Sub(ByVal M As String)
Log("Client:" & M)
End Sub)
End Sub)
T.Start()
End Sub
Private Sub button_server_init_Click(sender As Object, e As RoutedEventArgs) Handles button_server_init.Click
Server.Init(Port)
End Sub
Private Sub button_server_start_Click(sender As Object, e As RoutedEventArgs) Handles button_server_start.Click
Dim T As Thread = New Thread(Sub()
Server.Open()
End Sub)
T.Start()
End Sub
Private Sub button_server_write_Click(sender As Object, e As RoutedEventArgs) Handles button_server_write.Click
Server.Write("foo")
End Sub
Private Sub button_server_listen_Click(sender As Object, e As RoutedEventArgs) Handles button_server_listen.Click
Dim T As Thread = New Thread(Sub()
Server.Listen(Sub(ByVal M As String)
Log("Server: " & M)
End Sub)
End Sub)
T.Start()
End Sub
End Class
Edit:
I tried to do the whole thing with StreamReader/Writers. Now I am not even getting a síngle Message:
Server
Imports System.IO
Imports System.Net.Sockets
Public Class Server
Inherits ConnectionPartner
Private Server As TcpListener
Private Client As TcpClient
Private Reader As StreamReader
Private Writer As StreamWriter
Private Port As Integer
Public Sub Init(ByVal port As Integer)
Server = New TcpListener(port)
End Sub
Public Sub Open()
Server.Start()
Client = Server.AcceptTcpClient()
Dim Stream As NetworkStream = Client.GetStream()
Reader = New StreamReader(Stream)
Writer = New StreamWriter(Stream)
End Sub
Public Overrides Sub Write(ByVal Message As String)
Writer.WriteLine(Message)
End Sub
Public Overrides Sub Write(ByVal Message() As Byte)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
While True
Dim Message As String = Reader.ReadLine()
Handler(Message)
End While
End Sub
Public Overrides Sub Listen(ByRef Handler As Action(Of Byte()))
End Sub
Public Sub Close()
Try
Client.Close()
Catch ex As Exception
End Try
Try
Server.Stop()
Catch ex As Exception
End Try
End Sub
End Class
Client
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Client
Inherits ConnectionPartner
Private Socket As TcpClient
Private Reader As StreamReader
Private Writer As StreamWriter
Private Port As Integer
Public Sub Init()
Socket = New TcpClient()
End Sub
Public Sub Open(ByVal Ip As IPAddress, ByVal Port As Integer)
Socket.Connect(Ip, Port)
Dim Stream As NetworkStream = Socket.GetStream()
Reader = New StreamReader(Stream)
Writer = New StreamWriter(Stream)
End Sub
Public Overrides Sub Write(ByVal Message As String)
Writer.WriteLine(Message)
End Sub
Public Overrides Sub Write(ByVal Message() As Byte)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
While True
Dim Message As String = Reader.ReadLine()
Handler(Message)
End While
End Sub
Public Overrides Sub Listen(ByRef Handler As Action(Of Byte()))
End Sub
Public Sub Close()
Try
Socket.Close()
Catch ex As Exception
End Try
End Sub
End Class
Solution:
Forgot to flush the Messages.
Server
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Server
Inherits ConnectionPartner
Private Server As TcpListener
Private Client As TcpClient
Private Reader As StreamReader
Private Writer As StreamWriter
Private Port As Integer
Public Sub Init(ByVal Ip As IPAddress, ByVal Port As Integer)
Server = New TcpListener(Ip, Port)
End Sub
Public Sub Open()
Server.Start()
Client = Server.AcceptTcpClient()
Dim Stream As NetworkStream = Client.GetStream()
Reader = New StreamReader(Stream)
Writer = New StreamWriter(Stream)
Writer.AutoFlush = True
End Sub
Public Overrides Sub Start(ByVal Ip As IPAddress, ByVal Port As Integer)
Me.Init(Ip, Port)
Me.Open()
End Sub
Public Overrides Sub Write(ByVal Message As String)
Writer.WriteLine(Message)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
While True
Dim Message As String = Reader.ReadLine()
Handler(Message)
End While
End Sub
Public Overrides Sub Close()
Try
Client.Close()
Catch ex As Exception
End Try
Try
Server.Stop()
Catch ex As Exception
End Try
End Sub
End Class
Client
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Client
Inherits ConnectionPartner
Private Socket As TcpClient
Private Reader As StreamReader
Private Writer As StreamWriter
Private Port As Integer
Public Sub Init()
Socket = New TcpClient()
End Sub
Public Sub Open(ByVal Ip As IPAddress, ByVal Port As Integer)
Socket.Connect(Ip, Port)
Dim Stream As NetworkStream = Socket.GetStream()
Reader = New StreamReader(Stream)
Writer = New StreamWriter(Stream)
Writer.AutoFlush = True
End Sub
Public Overrides Sub Start(ByVal Ip As IPAddress, ByVal Port As Integer)
Me.Init()
Me.Open(Ip, Port)
End Sub
Public Overrides Sub Write(ByVal Message As String)
Writer.WriteLine(Message)
End Sub
Public Overrides Sub Listen(ByVal Handler As Action(Of String))
While True
Dim Message As String = Reader.ReadLine()
Handler(Message)
End While
End Sub
Public Overrides Sub Close()
Try
Socket.Close()
Catch ex As Exception
End Try
End Sub
End Class
TCP does not provide messages at all. It provides a boundaryless stream of bytes. When you Read you can get back any number of bytes as low as one. You code needs to assume arbitrary chunking. Here, you are assuming that you get a full buffer each time.
You can use BinaryReader.ReadBytes to read an exact number of bytes. StreamReader/Writer makes text-based protocols much easier.
ReceiveBufferSize is not the number of bytes incoming. It's value is meaningless, don't look at it.

HALCON error #8721: List of bar code models is empty

I have an error in my simple project. I use vb.net 2008 and the full error text is:
[HALCON error #8721: List of bar code models is empty at HALCONXLib.HBarCodeXClass.FindBarCode(HImageX Image, Object CodeType, Object& DecodedDataStrings)]
And my code is:
Option Strict Off
Option Explicit On
Imports HalconDotNet
Imports Microsoft
Imports System.Text
Imports System.IO
Imports System.Media
Imports System
Imports Microsoft.VisualBasic
Imports HALCONXLib
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim htu As HTupleX = New HTupleX
Dim reader As HBarCodeX = New HBarCodeX()
Dim Image As HImageX = New HImageX
Call Image.ReadImage("d:\barcode\image1.JPG")
Dim regions As HRegionX = New HRegionX
Try
regions = reader.FindBarCode(Image, "EAN-13", htu)
Catch ex As Exception
RichTextBox1.Text = ex.ToString
End Try
End Sub
End Class
I guess the call to
void HBarCodeX.CreateBarCodeModel(
[in] VARIANT GenParamNames, [in] VARIANT GenParamValues)
is missing to actually create the Reader.

Two way client and server?

I created a one way client server communication so that the client can send messages to the server which just receives them. How can I modify the code so that both the server and the client can send and receive messages.
Client Code:
TCPControl.vb
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Class TCPControl
Public Client As TcpClient
Public DataStream As StreamWriter
Public Sub New(Host As String, Port As Integer)
' CLIENT
Client = New TcpClient(Host, Port)
DataStream = New StreamWriter(Client.GetStream)
End Sub
Public Sub Send(Data As String)
DataStream.Write(Data & vbCrLf)
DataStream.Flush()
End Sub
End Class
Form1.vb
Public Class Form1
Private Client As TCPControl
Private Sub cmdSend_Click(sender As System.Object, e As System.EventArgs) Handles cmdSend.Click
SendMessage()
txtMessage.Clear()
txtMessage.Focus()
End Sub
Private Sub cmdConnect_Click(sender As System.Object, e As System.EventArgs) Handles cmdConnect.Click
Client = New TCPControl("10.0.0.253", 64555)
If Client.Client.Connected Then cmdConnect.Text = "Connected"
End Sub
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If Client.Client.Connected = True Then
Client.DataStream.Close()
Client.Client.Close()
End If
End Sub
Private Sub txtMessage_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtMessage.KeyDown
If e.KeyCode = Keys.Enter Then SendMessage()
End Sub
Private Sub SendMessage()
If Client.Client.Connected = True Then Client.Send(txtMessage.Text)
End Sub
End Class
Server Code:
TCPControl.vb
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class TCPControl
Public Event MessageReceived(sender As TCPControl, Data As String)
' SERVER CONFIG
Public ServerIP As IPAddress = IPAddress.Parse("10.0.0.253")
Public ServerPort As Integer = 64555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
' CLIENTS
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIP, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub
Private Sub Listening()
' CREATE LISTENER LOOP
Do Until IsListening = False
' ACCEPT INCOMING CONNECTIONS
If Server.Pending = True Then
Client = Server.AcceptTcpClient
ClientData = New StreamReader(Client.GetStream)
End If
' RAISE EVENT FOR INCOMING MESSAGES
Try
RaiseEvent MessageReceived(Me, ClientData.ReadLine)
Catch ex As Exception
End Try
' REDUCE CPU USAGE
'Thread.Sleep(100)
Loop
End Sub
End Class
Public Class Form1
Private Server As TCPControl
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Server.IsListening = False
End Sub
TCPControl.vb
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Server = New TCPControl
txtChat.Text = ":: SERVER STARTED ::" & vbCrLf
AddHandler Server.MessageReceived, AddressOf OnLineReceived
End Sub
' ALLOW THREAD TO COMMUNICATE WITH FORM CONTROL
Private Delegate Sub UpdateTextDelegate(TB As TextBox, txt As String)
' UPDATE TEXTBOX
Private Sub UpdateText(TB As TextBox, txt As String)
If TB.InvokeRequired Then
TB.Invoke(New UpdateTextDelegate(AddressOf UpdateText), New Object() {TB, txt})
Else
If txt IsNot Nothing Then TB.AppendText(txt & vbCrLf)
End If
End Sub
' UPDATE TEXT WHEN DATA IS RECEIVED
Private Sub OnLineReceived(sender As TCPControl, Data As String)
UpdateText(txtChat, Data)
End Sub
End Class