Server client application vb.net - 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

Related

how to close multi thread tcp listener

I worked on this listener ( I did not try to connect any clients to it until now).
I have this problem.
When starting the listener it started OK without any problem. so I added a stop listener button to this application and I tried to do listener.stop() but it throws an exception:
enter image description here
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
Until now I did not try to connect any client after the listener started, I only used start listener and stop listener buttons and the listener throws an exception.
How I gracefully shut down this listener without the exception ?
Imports System.IO, System.Net, System.Net.Sockets
Public Class frmServer
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ClientList As New List(Of ChatClient)
Dim sReader As StreamReader
Dim cClient As ChatClient
Sub xLoad() Handles Me.Load
Listener = New TcpListener(IPAddress.Any, 3818)
Listener.Start()
xUpdate("Server Started", False)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
AddHandler (cClient.MessageRecieved), AddressOf MessageRecieved
AddHandler (cClient.ClientExited), AddressOf ClientExited
ClientList.Add(cClient)
xUpdate("New Client Joined", True)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub MessageRecieved(ByVal Str As String)
xUpdate(Str, True)
End Sub
Sub ClientExited(ByVal Client As ChatClient)
ClientList.Remove(Client)
xUpdate("Client Exited", True)
End Sub
Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
Else
txtMainTextBox.AppendText(Str & vbNewLine)
If Relay Then Send(Str)
End If
End Sub
Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSendTextBox.KeyDown
End Sub
Sub Send(ByVal Str As String)
For i As Integer = 0 To ClientList.Count - 1
Try
ClientList(i).Send(Str)
Catch
ClientList.RemoveAt(i)
End Try
Next
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Me.txtSendTextBox.Text = "" Then
Exit Sub
End If
xUpdate("Server Says: " & Me.txtSendTextBox.Text, True)
txtSendTextBox.Clear()
End Sub
Private Sub btnStopListener_Click(sender As Object, e As EventArgs) Handles btnStopListener.Click
Listener.Stop()
'this part stopped the listener but it throws an exception
End Sub
End Class

No UDP packets received using async method 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)

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

How to send text throught pc's

Is there any way to send text throught PC's without a client and a server program? Just simply send text from a program to another.
Even though you don't want to use clients and servers, this is the easiest way to go.
The server is a server that runs in the command prompt, but runs in the background of your program. The server and client won't be visible in any way.
A simple answer with few lines of codes are TCP Communication. This uses the ip addresses of the both computers and establish a server/client connection.
Every communication needs something that hosts it, to achieve this you code the program to contain the following:
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim listener As New TcpListener(8000)
Dim Client As TcpClient
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
listener.Stop()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
listener.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim Data As String = ""
Dim nStart As Integer
Dim nLast As Integer
If listener.Pending = True Then
Client = listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream)
While Reader.Peek > -1
Data &= Convert.ToChar(Reader.Read()).ToString
End While
If Not Data = "" Then
msgbox("This is the data recieved: " & Data)
End If
End If
End Sub
End Class
This will open a "TCPListener" on the localhost port 8000. Whenever a client sends data to the listener, the text of the textbox Textbox1 to the data sent.
To send data to the server, use the following code:
Option Explicit On
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim Client As TcpClient
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
//Ip to the local or remote, forwarded server. 127.0.0.1 is localhost - the same machine.
Client = New TcpClient("127.0.0.1", 8000)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write("Hello World!")
Writer.Flush()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This will, when Button1 is pressed, try to send the data/string "Hello World!" to the server.
This could be combined into one by having the application set up as following:
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim listener As New TcpListener(8000)
Dim Client As TcpClient
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
listener.Stop()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
listener.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim Data As String = ""
Dim nStart As Integer
Dim nLast As Integer
If listener.Pending = True Then
Client = listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream)
While Reader.Peek > -1
Data &= Convert.ToChar(Reader.Read()).ToString
End While
If Not Data = "" Then
'Change the string
End If
TextBox1.Text = Data
End If
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
//This has to be the address to the remote
Client = New TcpClient("xx.xx.xx.xx", 8000)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write(TextBox2.Text)
Writer.Flush()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
To extend this and make it useable in a real application, use a backgroundworker to simply make the server and client run on another thread.
If you don't want to use socket or pipes, i can only think of files, which is more pc to pc than program to program.

Dispatcher.Invoke and accessing textbox from another thread

I am having a little trouble understanding how I should be utilizing the Dispatcher to help me solve my problem of accessing a text box from a different thread. What I am trying to achieve is getting the thread to append to a chat box once it receives data form the server.
Public Class ChatScreen
Public client As Client
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
client = Application.Current.Properties("Client")
Me.Title = "ChitChat - " & client.Name
txtMessage.Focus()
Dim serverHandler As New ServerHandler(client.clientSocket, client.networkStream, txtChat)
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSend.Click
client.SendMessage(txtMessage.Text)
End Sub
Private Sub Window_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles MyBase.KeyDown
If e.Key = Key.Enter Then
client.SendMessage(txtMessage.Text)
End If
End Sub
Public Sub AppendToChat(ByVal message As String)
txtChat.AppendText(">> " & message)
End Sub
Public Class ServerHandler
Dim clientSocket As TcpClient
Public networkStream As NetworkStream
Dim thread As Thread
Public Sub New(ByVal clientSocket As TcpClient, ByVal networkStream As NetworkStream)
Me.clientSocket = clientSocket
Me.networkStream = networkStream
thread = New Thread(AddressOf ListenForServer)
thread.Start()
End Sub
Public Sub ListenForServer()
Dim bytesFrom(10024) As Byte
Dim message As String
While True
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
message = System.Text.Encoding.ASCII.GetString(bytesFrom)
message = message.Substring(0, message.IndexOf("$"))
'AppendToChat <--- This is where I would like to append the message to the text box
End While
End Sub
End Class
End Class
You can use SynchronizationContext to do this,
Store UI tread context in a variable like this
Private syncContext As SynchronizationContext
Private Sub frmClient_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
syncContext = AsyncOperationManager.SynchronizationContext
End Sub
Now create a procedure to execute on main UI thread like this
Private Sub AddTextBox()
‘Do whatever you want you are in UI thread here
End Sub
From you background thread post request on UI thread like this
syncContext.Post(New SendOrPostCallback(AddressOf AddTextBox), Nothing)
you can even pass arguments also
Private Sub AddTextBox(ByVal argument As Object)
‘Do whatever you want you are in UI thread here
End Sub
.....
syncContext.Post(New SendOrPostCallback(AddressOf AddTextBox), objToPass)