Chat system with one or two ways? - vb.net

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

Related

VB LAN Messenger having issues

I have made a small LAN messenger and I tried it with two pc's and it didnt work however running two of the applications with one listening to port 40004 and writing to 40005 and one listening to 40005 and writing to 40004 works.
The problem seems to be in the sendb_click where I send the message. It says Receipent not connected.
Error message:
System.net.sockets.socketexception (0x80004005); No connection could be made
because the target machine actively refused it 127.0.0.1:40003
at system.net.sockets.tcpclient..ctor(string hostname,int32 port)
at messenger.form2.sendb_click(object sender, eventargs e) in
D:\Messenger\Messenger\Form2.vb:line 97
:Interface
When connected you can choose a computer that is connected to the network on the right and message it. Im planning on having generated ports or whatever but for testing ive just made 40004 and 40005 the ports.
What is going wrong? Do i have to port forward or something?
below is my code
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Imports System.Net.Dns
Imports System.DirectoryServices
Public Class Form2
Class entity
Public name As String
Public ip As String
Public port As Integer
End Class
Public reciepent As New entity
Public user As New entity
Public CLient As New TcpClient
Public listener As New TcpListener(40003)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
usernametb.Text = user.name
FindingThreats()
getmyip()
ipl.Text = user.ip
user.port = 40003
portl.Text = user.port
' listener = New TcpListener(40004)
Dim ListThread As New Thread(New ThreadStart(AddressOf Listening))
ListThread.Start()
End Sub
Private Sub Listening()
listener.Start()
End Sub
Sub FindingThreats()
UsersL.Items.Clear()
Dim childEntry As DirectoryEntry
Dim ParentEntry As New DirectoryEntry
Try
ParentEntry.Path = "WinNT:"
For Each childEntry In ParentEntry.Children
Select Case childEntry.SchemaClassName
Case "Domain"
Dim SubChildEntry As DirectoryEntry
Dim SubParentEntry As New DirectoryEntry
SubParentEntry.Path = "WinNT://" & childEntry.Name
For Each SubChildEntry In SubParentEntry.Children
Select Case SubChildEntry.SchemaClassName
Case "Computer"
UsersL.Items.Add(SubChildEntry.Name)
End Select
Next
End Select
Next
Catch Excep As Exception
MsgBox("Error While Reading Directories : " + Excep.Message.ToString)
Finally
ParentEntry = Nothing
End Try
End Sub
Sub getmyip()
For Each ip As Net.IPAddress In
GetHostEntry(GetHostName).AddressList
user.ip = ip.ToString
Next
End Sub
Sub getip(strhostname As String, returnip As String)
Try
returnip = GetHostByName(strhostname).AddressList(0).ToString()
reciepent.ip = returnip
Catch
MsgBox("This user is Offline.")
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles UsersL.SelectedIndexChanged
CUL.Items.Clear()
CUL.Items.Add("Connected Users:")
Dim ip As String
Dim hostname = UsersL.SelectedItem.ToString
getip(hostname, ip)
reciepent.port = 40004
Timer1.Enabled = True
CUL.Items.Add(user.name)
End Sub
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Me.Close()
End Sub
Private Sub SendB_Click(sender As Object, e As EventArgs) Handles SendB.Click
Try
CLient = New TcpClient("127.0.0.1", 40004) 'reciepent.port)
Dim Writer As New StreamWriter(CLient.GetStream())
Writer.Write(ChatB.Text)
ChatL.Items.Add("> " & ChatB.Text)
Writer.Flush()
Catch
MsgBox("Receipent not connected.")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim message As String
If listener.Pending = True Then
message = ""
CLient = listener.AcceptTcpClient()
Dim Reader As New StreamReader(CLient.GetStream())
While Reader.Peek > -1
message = message + Convert.ToChar(Reader.Read()).ToString
End While
ChatL.Items.Add("< " & message)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FindingThreats()
End Sub
Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
listener.Stop()
Me.Close()
End Sub
End Class

Send and receive data from a websocket server using sockets in Vb.net

i am new to network programming and would really appreciate your help to receive and send data to a server. I am trying to Use Sockets to Send and Receive data from a server which is developed using WebSockets.
Until now i have created the following Code which i think is wrong: in this code i am trying to send data on a normal thread but receive data on a different thread so that the program dont go on hold.
as i send data to the server, after some time i get this text reply on the textbox in which i am trying to receive the server response:
HTTP/1.1 501 Not Implemented
Any help will be much appreciated
TCPControl class(handles the connection, send and receive matters)
Public Class TCPControl
Public client As TcpClient
Public DataStream As StreamWriter
Private ReceiveData As StreamReader
Private comThread As Thread
Public isListening As Boolean = True
Public Event MessageReceived(sender As TCPControl, Data As String)
Public Sub New(Host As String, Port As Integer)
Try
client = New TcpClient(Host, Port)
DataStream = New StreamWriter(client.GetStream)
comThread = New Thread(New ThreadStart(AddressOf Listening))
comThread.Start()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Listening()
Do Until isListening = False
If client.Connected = True Then
ReceiveData = New StreamReader(client.GetStream)
End If
Try
RaiseEvent MessageReceived(Me, ReceiveData.ReadLine)
Catch ex As Exception
End Try
Thread.Sleep(10)
Loop
End Sub
Public Sub Send(Data As String)
DataStream.Write(Data & vbCrLf)
DataStream.Flush()
End Sub End Class
Form1 class(handles form load and other stuff)
Public Class Form1
Private client As TCPControl
' Private receiveClient As TCPControlReceive
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' client = New TCPControl("174.129.224.73", 80)
client = New TCPControl(GetIpAddress("echo.websocket.org").ToString, 80)
If client.client.Connected Then Label1.Text = "Connected"
'receiveClient = New TCPControlReceive
AddHandler client.MessageReceived, AddressOf OnLineReceived
End Sub
Private Delegate Sub UpdateMessageDelegate(TB As TextBox, txt As String)
Private Sub UpdateText(TB As TextBox, txt As String)
If TB.InvokeRequired Then
TB.Invoke(New UpdateMessageDelegate(AddressOf UpdateText), New Object() {TB, txt})
Else
If txt IsNot Nothing Then
TB.AppendText(txt & vbCrLf)
End If
End If
End Sub
Private Sub OnLineReceived(sender As TCPControl, Data As String)
UpdateText(txtReceive, Data)
End Sub
Private Function GetIpAddress(address As String) As IPAddress
Dim ips As IPAddress()
ips = Dns.GetHostAddresses(address)
Return ips(0)
End Function
Private Sub SendMessage()
If client.client.Connected = True Then
client.Send(txtSend.Text)
End If
End Sub
Private Sub Form1_ContextMenuStripChanged(sender As Object, e As EventArgs) Handles Me.ContextMenuStripChanged
If client.client.Connected = True Then
client.DataStream.Close()
client.Client.Close()
End If
client.isListening = False
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
SendMessage()
txtSend.Clear()
End Sub End Class
'HTTP/1.1 501 Not Implemented' was sent by the server, not generated by VB.
I would assume from this that your code works fine, and the problem lies with the command(s) you are sending after the client connects.

Tcp Client/Server - Client messages issue

I have client and server application.
I have the client disconnect from the server with client.close via a disconnect button.
I send a message, shows on server. ok works great.
I disconnect and then reconnect. I send a message. It shows the message two times.
I disconnect another time then reconnect. I send a message. It then shows the message three times.
It is incrementing the message and sending it multiple times after the disconnect and then reconnect.
Help? Been trying to figure this out for a while
[SERVER]
Public Class Server
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ListenerThread As System.Threading.Thread
Dim ClientID As String
Dim ClientIP As String
Dim ClientIPandID As String
Dim ClientIPandPort As String
Dim TotalItemCount As String
Dim clientcount As Integer = 0
Private Sub Server_Load(sender As Object, e As EventArgs) Handles Me.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub ButtonStart_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStart.Click
If TextBoxPort.Text = "" Then
MsgBox("Please Enter Port To Run On.")
Else
ListenerThread = New System.Threading.Thread(AddressOf Listening)
ListenerThread.IsBackground = True
ListenerThread.Start(TextBoxPort.Text)
ButtonStart.Enabled = False
ButtonStop.Enabled = True
ListBox1.Items.Add("[SERVER] Running on Port " + TextBoxPort.Text)
ListBox1.Items.Add("[SERVER] Waiting For A Connection...")
End If
End Sub
Private Sub Listening(ByVal Port As Integer)
Try
Listener = New TcpListener(IPAddress.Any, Port)
Listener.Start()
Do
Client = Listener.AcceptTcpClient 'Accepts Client Trying To Connect
If Client.Connected Then
MsgBox("Client Connected")
End If
clientcount += 1
GetClientInfo() 'Retrieves The Clients Info
AddHandler ReceivedMessage, AddressOf ReceivedMessage1
Loop Until False
Catch ex As Exception
End Try
End Sub
'Events
Public Event ReceivedMessage(ByVal Command As String)
Private Sub GenerateClientSessionNumber()
Dim r As New Random
Dim x As String = String.Empty
For i = 0 To 7
x &= Chr(r.Next(65, 89))
Next
ClientID = x
End Sub
Private Sub GetClientInfo()
GenerateClientSessionNumber()
ClientIPandID = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":")) & " - " & ClientID
ClientIP = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":"))
ClientIPandPort = Client.Client.RemoteEndPoint.ToString()
MsgBox(ClientIPandPort)
ListBox2.Items.Add(ClientIPandID)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
End Sub
Private Sub ButtonStop_Click(sender As System.Object, e As System.EventArgs) Handles ButtonStop.Click
Listener.Stop()
Client.Close()
ButtonStop.Enabled = False
ButtonStart.Enabled = True
ListBox1.Items.Add("[SERVER] Server Stopped")
End Sub
Private Sub Reading()
Try
Dim Reader As New StreamReader(Client.GetStream)
Dim Command As String = Reader.ReadLine
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
RaiseEvent ReceivedMessage(command)
Catch ex As Exception
End Try
End Sub
Private Sub ReceivedMessage1(ByVal Command As String)
Dim Message() As String = Command.Split("|")
If Message(0) = "MESSAGE" Then
MsgBox("Message Received From Client " + ">" + Message(1))
End If
end sub
[CLIENT]
Public Class Client
Dim Client As New TcpClient
Sub Connect(ByVal ServerIP As String, ByVal Port As Integer)
'Try To Make Connection With Server
If Client.Connected = True Then
MsgBox("Already Connected")
MsgBox("Connected To " + Client.Client.RemoteEndPoint.ToString)
Else
MsgBox("Currently Not Connected. Trying To Connect...")
Try
Client.Connect(ServerIP, Port)
MsgBox("Connected")
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
Catch ex As Exception
MsgBox("Could Not Connect To Server. Check Server." + ex.Message.ToString)
End Try
End If
End Sub
Private Sub SendData(ByVal Message As String) 'Sends Data to Server
TextBox1.Text = Message
Try
If Client.Connected = True Then
Dim Writer As New StreamWriter(Client.GetStream)
Writer.WriteLine(Message)
Writer.Flush()
Else
MsgBox("Cannot Send Message. Connection To Server Is Not Active.")
End If
Catch ex As Exception
MsgBox("You Are Not Connected To The Server." + vbCrLf + ex.Message.ToString)
End Try
End Sub
Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
Connect(TextBoxIPAddress.Text, TextBoxPort.Text)
End Sub
Private Sub ButtonSendMessage_Click(sender As Object, e As EventArgs) Handles ButtonSendMessage.Click
SendData("MESSAGE|" & TextBoxMessage.Text)
End Sub
Private Sub Client_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
SendData("DISCONNECT|")
Client.Close()
Client = New TcpClient
End Sub
End Class
i am not sure about the problem but i can give you some hypothesizes, firstly you add handler on every client you connect on server side and that means multiple pointer to the same place, secondly when you connect to server and reconnect you actually don't tell the server that the two clients are the same so he make two channels between the client and the server, the first is the old one that didn't close and he still have handler on it, the server don't recognize that the first is disconnected because he is connected! even if its another object at client. so when client disconnects , disconnect him from server too, or at every loop test if clients are connected before accepting do this test .
Since I have a class Called "ConnectedClient". I was able to make a call to that specific client or all clients and Close/Destroy the connection.

Client/Server application with VB.NET [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a problem in my VB.NET server/client chat application.
The problem happens when I send some information from the client application to the server application. I successfully established the connection and sent a message, but instead of showing that message, it's showing the name of my form server.
Public Class Form1
Private Server As TCPControl
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Server.IsListening = False
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Server = New TCPControl ' fires new sub
txtChat.Text = " :: SERVER STARTED :: " & vbCrLf
AddHandler Server.MessageRecived, AddressOf OnLineRecived
End Sub
'da se uspijesno prenesu informacije na kontrolu
Private Delegate Sub UpdateTextDelegate(ByVal tb As TextBox, ByVal txt As String)
'UPDATE TEXTBOX
Private Sub UpdateText(ByVal tb As TextBox, ByVal txt As String)
If tb.InvokeRequired Then 'HERE I SEE MY MESSAGE FROM CLIENT APLICATION
tb.Invoke(New UpdateTextDelegate(AddressOf UpdateText), New Object() {tb, txt})
Else
If txt IsNot Nothing Then tb.AppendText(Text & vbCrLf)
End If
End Sub
Private Sub OnLineRecived(ByVal sender As TCPControl, ByVal data As String)
UpdateText(txtChat, data) 'HERE I SEE MY MESSAGE FROM CLIENT APLICATION
End Sub
End Class
Public Class TCPControl
Public Event MessageRecived(ByVal sender As TCPControl, ByVal data As String)
'SERVER CONFIG
Public ServerIp As IPAddress = IPAddress.Parse("192.168.1.108")
Public ServerPort As Integer = 46555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
'CLIENTS (samo ce prihvatiti jednog klijenta)
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 LISTENAR LOOP
Do Until IsListening = False
' ACCEPT INCOMING CONNECTIONS
If Server.Pending = True Then
Client = Server.AcceptTcpClient
ClientData = New StreamReader(Client.GetStream)
End If
'RAISE EVANT FOR INCOMING MESSAGES
Try
RaiseEvent MessageRecived(Me, ClientData.ReadLine) ' now is displying the name of server form
Catch ex As Exception
End Try
'REDUCE CPU USAGE
Thread.Sleep(100)
Loop
End Sub
End Class
There is an error when you update client TextBox on UpdateText.
If tb.InvokeRequired Then
tb.Invoke(New UpdateTextDelegate(AddressOf UpdateText), New Object() {tb, txt})
Else
If txt IsNot Nothing Then tb.AppendText(Text & vbCrLf) ' Here
End If
Change Text with txt.
If txt IsNot Nothing Then tb.AppendText(txt & vbCrLf)

vb.net server - multiple clients continually processing different information

I am looking for help with writing a server application to serve an updating text stream to clients. My requirements are as follows:
I need to be able to have a client request information on server port 7878 and receive back an initial set of values, the changed values would then be reported every 5 seconds. The hanging point for me has been connecting another client. I need to be able to connect a 2nd (or 3rd or 4th) client while the first is still running. The second client would receive the initial values and then begin updating as well. I need the two streams to be completely independent of each other. Is this possible with VB.Net and TCP sockets?
Edit to add: I have pasted some of my code below of what I can share. WriteLog is a separate sub that isn't really relevant to my problem. This code will allow for a client to connect and then allow for another client to connect, but all transmissions to the 1st client stop on a new connection.
Public Class ServerApp
Dim serverSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Private Sub ServerApp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WriteLog(String.Format("Start of form load.."))
Dim listener As New Thread(New ThreadStart(AddressOf ListenForRequests))
listener.IsBackground = True
listener.Start()
End Sub
Private Sub ListenForRequests()
Dim CONNECT_QUEUE_LENGTH As Integer = 4
serverSocket.Bind(New IPEndPoint(IPAddress.Any, 7878))
serverSocket.Listen(CONNECT_QUEUE_LENGTH)
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)
WriteLog("just accepted new client")
Try
clientSocket.Send(Encoding.UTF8.GetBytes("first response on connect"), SocketFlags.None)
While True
clientSocket.Send(Encoding.UTF8.GetBytes("string of updates"), SocketFlags.None)
Thread.Sleep(5000)
End While
Catch ex As Exception
WriteLog(ex.Message)
WriteLog("Remote host has disconnected")
End Try
End Sub
End Class
I recommend trying out the UdpClient class, i find it easier to use and understand.
Now for some code...
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Public Class Form1
Private port As Integer = 7878
Private Const broadcastAddress As String = "255.255.255.255"
Private receivingClient As UdpClient
Private sendingClient As UdpClient
Private myTextStream As String = "Blah blah blah"
Private busy As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
InitializeSender()
InitializeReceiver()
End Sub
Private Sub InitializeSender()
Try
sendingClient = New UdpClient(broadcastAddress, port)
sendingClient.EnableBroadcast = True
Catch ex As Exception
MsgBox("Error, unable to setup sender client on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
End Try
End Sub
Private Sub InitializeReceiver()
Try
receivingClient = New UdpClient(port)
ThreadPool.QueueUserWorkItem(AddressOf Receiver)
Catch ex As Exception
MsgBox("Error, unable to setup receiver on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
End
End Try
End Sub
Private Sub sendStream()
busy = True
Dim i% = 0
Do While i < 4
If myTextStream <> "" Then
Dim data() As Byte = Encoding.ASCII.GetBytes(myTextStream)
Try
sendingClient.Send(data, data.Length)
Catch ex As Exception
MsgBox("Error, unable to send stream." & vbNewLine & vbNewLine & ex.ToString)
End
End Try
End If
Thread.Sleep(5000)
i += 1
Loop
busy = False
End Sub
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port)
While True
Dim data() As Byte
data = receivingClient.Receive(endPoint)
Dim incomingMessage As String = Encoding.ASCII.GetString(data)
If incomingMessage = "what ever the client is requesting, for example," & "GET_VALUES" Then
If busy = False Then Call sendStream()
End If
End While
End Sub
End Class
A few links that may help: Here,
here,
here and
here.