VB.
NET Client-Server Application with Key Press Simulation
This guide provides step-by-step instructions and VB.NET code to create a simple client-server
application. The client sends a request to the server, and the server simulates a key press upon
receiving the request.
Server Application (VB.NET)
1. Open Visual Studio and create a new Console App (.NET Framework) project.
2. Copy and paste the following code into the Module1.vb file.
3. Run the server application. It will listen on port 5000 for incoming client requests.
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module ServerApp
Dim listener As TcpListener
Dim port As Integer = 5000
Sub Main()
listener = New TcpListener(IPAddress.Any, port)
listener.Start()
Console.WriteLine($"Server listening on port {port}...")
While True
Dim client As TcpClient = listener.AcceptTcpClient()
Dim thread As New Thread(AddressOf HandleClient)
thread.Start(client)
End While
End Sub
Sub HandleClient(client As TcpClient)
Try
Dim stream As NetworkStream = client.GetStream()
Dim buffer(1024) As Byte
Dim bytesRead As Integer = stream.Read(buffer, 0, buffer.Length)
Dim data As String = Encoding.UTF8.GetString(buffer, 0, bytesRead)
If data.Trim() = "KEY_PRESS" Then
SimulateKeyPress("A")
Console.WriteLine("Key 'A' pressed.")
End If
Dim response As Byte() = Encoding.UTF8.GetBytes("Key press simulated")
stream.Write(response, 0, response.Length)
client.Close()
Catch ex As Exception
Console.WriteLine($"Error: {ex.Message}")
End Try
End Sub
Sub SimulateKeyPress(key As String)
My.Computer.Keyboard.SendKeys(key)
End Sub
End Module
Client Application (VB.NET)
1. Open Visual Studio and create a new Windows Forms App (.NET Framework) project.
2. Design a form with one button named 'btnSendRequest'.
3. Copy and paste the following code into the Form1.vb file.
4. Run the client application and click the button to send a request to the server.
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class ClientApp
Private Sub btnSendRequest_Click(sender As Object, e As EventArgs) Handles
btnSendRequest.Click
Dim serverIp As String = "127.0.0.1"
Dim port As Integer = 5000
Try
Using client As New TcpClient(serverIp, port)
Dim stream As NetworkStream = client.GetStream()
Dim message As Byte() = Encoding.UTF8.GetBytes("KEY_PRESS")
stream.Write(message, 0, message.Length)
Dim buffer(1024) As Byte
Dim bytesRead As Integer = stream.Read(buffer, 0, buffer.Length)
Dim response As String = Encoding.UTF8.GetString(buffer, 0, bytesRead)
MessageBox.Show(response, "Response from Server")
End Using
Catch ex As Exception
MessageBox.Show($"Error: {ex.Message}", "Error")
End Try
End Sub
End Class