-
[RESOLVED] [2008] Can I add a TCPClient Component
Im learning Tcp communication right now, and Im a newbie :P
First can i add a component to the form for tcpclient and tcpserver like a add one for a textbox and a botton?
Second, which method is better
Dim listener As Net.Sockets.TcpListener
Dim listenThread As Threading.Thread
or Dim tcpClient As New System.Net.Sockets.TcpClient()
what should i use?
-
Re: [2008] Can I add a TCPClient Component
It matters what you are trying to accomplish with your program. Do you want the listener on a different thread?
"First can i add a component to the form for tcpclient and tcpserver like a add one for a textbox and a botton?"
Do you mean drag and drop?
-
Re: [2008] Can I add a TCPClient Component
yes i mean drag and drop
and what i want to do is 2 simple programs that send strings to each others.
-
Re: [2008] Can I add a TCPClient Component
The TcpClient is not a control that can be dragged onto the form, its a class of which you create an instance at runtime and use however you want.
-
Re: [2008] Can I add a TCPClient Component
ok, now can somone give me the simplest example possible :P
Please
Client:
How To connect
Send Data
Recieve Data
Server:
How To listen
Send Data
Receive Data
Ive searched the form and google, but Im not understanding the code :S
I need something very simple
-
Re: [2008] Can I add a TCPClient Component
There are so many examples all over this forum, it shouldnt be needed to create yet another one.
-
Re: [2008] Can I add a TCPClient Component
The MSDN Library documentation contains examples too. Have you read the documentation?
Note that a class must inherit, either directly or indirectly, the System.ComponentModel.Component class in order to be created in the designer. The System.Windows.Forms.Control class inherits Component, so all controls can be added in the designer. If you ever want to know whether a class can be created in the designer in future you don't need to ask. Simply open its MSDN documentation and check its ancestry for the Component class.
-
Re: [2008] Can I add a TCPClient Component
so I will follow Atheist's example since it looks pretty simple
The client side would be then
Code:
Dim listener As Net.Sockets.TcpListener Dim listenThread As Threading.Thread Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load listener = New Net.Sockets.TcpListener("127.0.0.1", 32111) listener.Start() listenThread = New Threading.Thread(AddressOf DoListen) listenThread.IsBackground = True listenThread.Start() End Sub
The Server side would be
Code:
Dim listener As Net.Sockets.TcpListener
Private Sub DoListen() 'This is the sub that does all the actual "listening". Its an endless loop that calls the AcceptTcpClient method over and over. 'If there is no connecting TcpClient, it will raise an exception but we will ignore this by catching it in a try statement and doing nothing with it. 'On the other hand, If a client has connected, it proceeds to the next line and a streamreader reads the incoming stream and shows it in a messagebox. Dim sr As IO.StreamReader Do Try Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient sr = New IO.StreamReader(client.GetStream) MessageBox.Show(sr.ReadToEnd) sr.Close() Catch End Try Loop End Sub
right?
this will only connect the two programs?
how to send information after connection?
-
Re: [2008] Can I add a TCPClient Component
Did you look at msdn's 101 code examples? The Sockets example shows you how to do all of this, including sending messages back and forth, in a simplistic manner.
-
Re: [2008] Can I add a TCPClient Component
Try winsocket.
http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip
Its much easier to use when you dont know anything about networking(programming) and if you would understand you should write something like this on your own anyway.
Gl with it
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by ovanwijk
Yes he could use this, but since he said he was learning TCP communications i highly suggest learning how to use the classes in the System.Net.Socket namespace, because:
1. They provide much more functionallity and flexibility.
2. If you dont learn the basics of Tcp communications in .Net and begin using a component like this, as soon as you want to make the slightest change in how the Winsock component works, you're gonna get stuck.
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
so I will follow
Atheist's example since it looks pretty simple
The client side would be then
Code:
Dim listener As Net.Sockets.TcpListener Dim listenThread As Threading.Thread Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load listener = New Net.Sockets.TcpListener("127.0.0.1", 32111) listener.Start() listenThread = New Threading.Thread(AddressOf DoListen) listenThread.IsBackground = True listenThread.Start() End Sub
The Server side would be
Code:
Dim listener As Net.Sockets.TcpListener
Private Sub DoListen() 'This is the sub that does all the actual "listening". Its an endless loop that calls the AcceptTcpClient method over and over. 'If there is no connecting TcpClient, it will raise an exception but we will ignore this by catching it in a try statement and doing nothing with it. 'On the other hand, If a client has connected, it proceeds to the next line and a streamreader reads the incoming stream and shows it in a messagebox. Dim sr As IO.StreamReader Do Try Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient sr = New IO.StreamReader(client.GetStream) MessageBox.Show(sr.ReadToEnd) sr.Close() Catch End Try Loop End Sub
right?
this will only connect the two programs?
how to send information after connection?
My example was very basic and needs some adjustment to be more effective. But basically the server side should have a TcpListener listening on a specified port and the client side should have a TcpClient connecting to the server on the same port.
-
Re: [2008] Can I add a TCPClient Component
i dont need it to be more effective. im still trying to make my client and server connect!!
so the code u provide is only for the server not the client... ? right?
im not understanding the code... is it for 2 programs or is it only for the server?
if its only for the server, could you PLEASE show me how a client would connect..
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
i dont need it to be more effective. im still trying to make my client and server connect!!
so the code u provide is only for the server not the client... ? right?
im not understanding the code... is it for 2 programs or is it only for the server?
if its only for the server, could you PLEASE show me how a client would connect..
In the specific post by me that you linked too, there is only code for the server side. But in the same thread, I've got examples for the client side aswell.
Anyway, I'll create one more example..
Server side:
Form:
VB.Net Code:
Public Class Form1
Private listener As System.Net.Sockets.TcpListener
Private listenThread As System.Threading.Thread
Private clients As New List(Of ConnectedClient) 'This list will store all connected clients.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
listener.Start() 'Start listening.
listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
listenThread.Start() 'Start executing doListen on the worker thread.
End Sub
Private Sub doListen()
Dim incomingClient As System.Net.Sockets.TcpClient
Do
incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
Dim connClient As New ConnectedClient(incomingClient, Me) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
AddHandler connClient.dataReceived, AddressOf Me.messageReceived
clients.Add(connClient) 'Adds the connected client to the list of connected clients.
Loop
End Sub
Public Sub removeClient(ByVal client As ConnectedClient)
If clients.Contains(client) Then
clients.Remove(client)
End If
End Sub
Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
'A message has been received from one of the clients.
'To determine who its from, use the sender object.
'sender.SendMessage can be used to reply to the sender.
Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
Select Case data(0)
Case "CONNECT"
'We use GetClientByName to make sure no one else is using this username.
'It will return Nothing if the username is free.
'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
If GetClientByName(data(1)) Is Nothing Then
'The username is not taken, we can safely assign it to the sender.
sender.Username = data(1)
End If
Case "DISCONNECT"
removeClient(sender)
End Select
End Sub
Private Function GetClientByName(ByVal name As String) As ConnectedClient
For Each cc As ConnectedClient In clients
If cc.Username = name Then
Return cc 'client found, return it.
End If
Next
'If we've reached this part of the method, there is no client by that name
Return Nothing
End Function
End Class
ConnectedClient class:
VB.Net Code:
Public Class ConnectedClient
Private mClient As System.Net.Sockets.TcpClient
Private mUsername As String
Private mParentForm As Form1
Private readThread As System.Threading.Thread
Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
Public Event dataReceived(ByVal sender As ConnectedClient, ByVal message As String)
Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As Form1)
mParentForm = parentForm
mClient = client
readThread = New System.Threading.Thread(AddressOf doRead)
readThread.IsBackground = True
readThread.Start()
End Sub
Public Property Username() As String
Get
Return mUsername
End Get
Set(ByVal value As String)
mUsername = value
End Set
End Property
Private Sub doRead()
Const BYTES_TO_READ As Integer = 255
Dim readBuffer(BYTES_TO_READ) As Byte
Dim bytesRead As Integer
Dim sBuilder As New System.Text.StringBuilder
Do
bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
If (bytesRead > 0) Then
Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
'The first element in the subMessages string array must be the last part of the current message.
'So we append it to the StringBuilder and raise the dataReceived event
sBuilder.Append(subMessages(0))
RaiseEvent dataReceived(Me, sBuilder.ToString)
sBuilder = New System.Text.StringBuilder
'If there are only 2 elements in the array, we know that the second one is an incomplete message,
'though if there are more then two then every element inbetween the first and the last are complete messages:
If subMessages.Length = 2 Then
sBuilder.Append(subMessages(1))
Else
For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
RaiseEvent dataReceived(Me, subMessages(i))
Next
sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
End If
Else
'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
sBuilder.Append(message)
End If
End If
Loop
End Sub
Public Sub SendMessage(ByVal msg As String)
Dim sw As IO.StreamWriter
Try
SyncLock mClient.GetStream
sw = New IO.StreamWriter(mClient.GetStream) 'Create a new streamwriter that will be writing directly to the networkstream.
sw.Write(msg)
sw.Flush()
End SyncLock
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
'As opposed to writing to a file, we DONT call close on the streamwriter, since we dont want to close the stream.
End Sub
End Class
Client Side:
Form:
VB.Net Code:
Public Class Form1
Private client As System.Net.Sockets.TcpClient
Private Const BYTES_TO_READ As Integer = 255
Private readBuffer(BYTES_TO_READ) As Byte
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
client = New System.Net.Sockets.TcpClient("localhost", 43001)
client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing)
End Sub
Private Sub doRead(ByVal ar As System.IAsyncResult)
Dim totalRead As Integer
Try
totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
End Try
If totalRead > 0 Then
'the readBuffer array will contain everything read from the client.
Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
messageReceived(receivedString)
End If
Try
client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
Catch ex As Exception
'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
'to this client and remove it from the list of connected clients.
End Try
End Sub
Private Sub messageReceived(ByVal message As String)
MessageBox.Show(message)
End Sub
Private Sub SendMessage(ByVal msg As String)
Dim sw As IO.StreamWriter
Try
sw = New IO.StreamWriter(client.GetStream)
sw.Write(msg)
sw.Flush()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class
You need to add more exception handling and possibly some SyncLocks upon accessing the different Streams. There are also some important things that I've left out, such as removing a client from the list of connected client upon disconnection.
I've tried to put some comments in the code but dont hesitate to look the different methods/classes up on MSDN.
Edit: I intend to update this example some day soon.
-
Re: [2008] Can I add a TCPClient Component
thanks a million
I will check this code and reply asap
thanks again
-
Re: [2008] Can I add a TCPClient Component
ok ur code is perfect, just what i wanted
now i have few questions:
1) Im getting an error
Cross-thread operation not valid: Control 'LblConnection' accessed from a thread other than the thread it was created on.
when I did this:
Code:
Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String) 'A message has been received from one of the clients. 'To determine who its from, use the sender object. 'sender.SendMessage can be used to reply to the sender.
Select Case Message
Case "/Connect"
sender.SendMessage("/Connected")
LblConnection.Text = "Connected"
Case Else
txtMain.Text = txtMain.Text & Message & vbNewLine
End Select
End Sub
2) after the server and the client are connected properly...
how can I send more msgs from the server
how can I reiceive more msgs on the client
ur code seems only to work for the first msg??
thx
-
Re: [2008] Can I add a TCPClient Component
1.
That is because all socket code is running on a separate thread, in order to access the controls you need to use Invoke. Heres an example that will fix the problem you posted:
VB.Net Code:
Private Delegate Sub StringDelegate(text As String)
Private Sub SetConnectionLabelText(text As String)
If Me.LblConnection.InvokeRequired Then
Me.Invoke(New StringDelegate(AddressOf SetConnectionLabelText), text)
Else
Me.LblConnection.Text = text
End If
End Sub
Now instead of doing:
VB.Net Code:
LblConnection.Text = "Connected"
Do:
VB.Net Code:
SetConnectionLabelText("Connected")
2.
If you want to send messages from the server, simply iterate through the list of connected clients and call the SendMessage method on the client you want to send a message to.
EDIT: Oh, I see that I've made a silly misstake in my code. Try it now.
-
Re: [2008] Can I add a TCPClient Component
well.. can u elaborate more?
Code:
Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
If txtSend.Text <> "" Then
' ????? should i use client.?????
End If
End Sub
-
Re: [2008] Can I add a TCPClient Component
Elaborate more? He just told you exactly what to do. What are you having problems with?
-
Re: [2008] Can I add a TCPClient Component
how to iterate through the list of connected clients ...
sorry but its really not easy for me
-
Re: [2008] Can I add a TCPClient Component
You see, this is a collection:
VB.Net Code:
Private clients As New List(Of ConnectedClient)
You can iterate through collections like this:
VB.Net Code:
For Each cc As ConnectedClient In clients
cc.SendMessage("this is a test")
Next
This will send a message to all connected clients.
-
Re: [2008] Can I add a TCPClient Component
i have another question
when i send a msg from the client to the server using this code
Code:
Private Sub SendMessage(ByVal Msg As String)
Dim sw As IO.StreamWriter
Try
sw = New IO.StreamWriter(client.GetStream)
sw.Write(msg)
sw.Flush()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I have to send the msg twice for it to reach the server
its like this, firsrt the two programs connect and the client send "/connect" and the server recieves it, then whatever the client sends the server doesnt recieve it.
the third msg is recieved, the fourth is not....
why is this happeneing?
2) how to read msgs in the client program?? my client only sends now...
should I create a Public Class ConnectedClient in the client program also?
-
Re: [2008] Can I add a TCPClient Component
About your first question, it was a small misstake I had made in the code that is now fixed, I've edited the original code in my previous post.
As for your second question, I cant see how I forgot to add that, hold on..
-
Re: [2008] Can I add a TCPClient Component
There, I've edited the code to handle incoming messages on the client side.
-
Re: [2008] Can I add a TCPClient Component
handling incoming messages worked perfectly... but am I blind because I cant see any difference in the rest of the code?
what should I chage to stop sending the msg twice before it was read?
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
handling incoming messages worked perfectly... but am I blind because I cant see any difference in the rest of the code?
what should I chage to stop sending the msg twice before it was read?
I made a small change in the doListen subroutine on the server side.
-
Re: [2008] Can I add a TCPClient Component
THANKS...............
thanks a million, the program works fine now
I still have a couple questions to improve the code now :P
first, on the server side,
how to see the ConnectedClient List? (for example put it in ListBox1) so we can send seperate msgs?
thanks agian
-
Re: [2008] Can I add a TCPClient Component
Well, since you dont have any good unique identifier like a username or something of the sort, you have 3 options:
1. Simply add each ConnectedClient instance in the collection to the Listbox, since the listbox can have any kind of object added to it. This wont be pretty as each item will look the same in the listbox..something like this: [ProjectName].UserConnection
The only advantage is that the listbox will return a ConnectedClient in the SelectedItem property that you can use easily:
VB.Net Code:
Ctype(ListBox1.SelectedItem, ConnectedClient).SendMessage("hello")
2. This is another option:
VB.Net Code:
For i As Integer = 0 To clients.Count-1
ListBox1.Items.Add(i)
Next i
Each client will now be represented by their index in the listbox. To send a message to a client by index you do:
VB.Net Code:
clients.item(Cint(ListBox1.SelectedItem)).SendMessage("hello")
3. The final option: This is the best option if you want to be able to identify a specific client from the rest.
Upon connection, have the client send a username that it wants to use. The server receives the username, checks so that it isnt already in use, then assigns it to the instance of ConnectedClient from which the message was received. This username can then be used to display every client in a list.
-
Re: [2008] Can I add a TCPClient Component
ok so Im tring to build the third option
so I have this code
Code:
Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String) 'A message has been received from one of the clients. 'To determine who its from, use the sender object. 'sender.SendMessage can be used to reply to the sender.
If Mid(Message, 1, 1) = "/" Then
Select Case Mid(Message, 2, 8)
Case "Connect:"
sender.SendMessage("/Connected")
SetConnectionLabelText("Connected")
Case Else
WriteToMainText(Message)
End Select
End If
End Sub
considering the cilent send "/Connect:USERNAME" when it connects
how to add the username to the list?
I was checking ur previous topic and u had a different diclaration
Dim Clients As New Dictionary(Of String, Net.Sockets.TcpClient)
whats the difference?
and u added the name in DoListen Sub not MessageReceived Sub?
what should I do?
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
ok so Im tring to build the third option
so I have this code
Code:
Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String) 'A message has been received from one of the clients. 'To determine who its from, use the sender object. 'sender.SendMessage can be used to reply to the sender.
If Mid(Message, 1, 1) = "/" Then
Select Case Mid(Message, 2, 8)
Case "Connect:"
sender.SendMessage("/Connected")
SetConnectionLabelText("Connected")
Case Else
WriteToMainText(Message)
End Select
End If
End Sub
considering the cilent send "/Connect:USERNAME" when it connects
how to add the username to the list?
I was checking ur previous topic and u had a different diclaration
Dim Clients As New Dictionary(Of String, Net.Sockets.TcpClient)
whats the difference?
and u added the name in DoListen Sub not MessageReceived Sub?
what should I do?
Alright, start by creating a string variable for holding the username in the ConnectedClient class, and create a string property for it. (If you dont know how, I'll shortly update my example). This variable will (obviously) hold the clients username.
Heres a method of handling messages used in MSDN 101 examples:
Send the messages with the | character as separator. If the user wants to connect with a username he'd send this: "CONNECT|MyName"
Your messageReceived method would then look like this:
VB.Net Code:
Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
'A message has been received from one of the clients.
'To determine who its from, use the sender object.
'sender.SendMessage can be used to reply to the sender.
Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
Select Case data(0)
Case "CONNECT"
'We use GetClientByName to make sure no one else is using this username.
'It will return Nothing if the username is free.
'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
If GetClientByName(data(1)) Is Nothing Then
'The username is not taken, we can safely assign it to the sender.
sender.Username = data(1)
End If
End Select
End Sub
Private Function GetClientByName(ByVal name As String) As ConnectedClient
For Each cc As ConnectedClient In clients
If cc.Username = name Then
Return cc 'client found, return it.
End If
Next
'If we've reached this part of the method, there is no client by that name
Return Nothing
End Function
Note the GetClientByName function, it will be useful later aswell.
About my use of the Dictionary in the other example, it provides the functionallity to store items in a collection and let each item have a (in this case) string key to identify them. We could've used that in this code aswell, but I chose the List instead.
Also, ignore all my other code in that example, the examples in there are fairly simple and nothing you should be using.
-
Re: [2008] Can I add a TCPClient Component
Hey there i did something like atheist did 2.
I personaly did it with creating a new class wich has as property ConnectedClient or a connected socket or something.(notice i worked with winsock so my own class had a connected winsock class in it) This way you can store anything you like from that user even if you want (while making a game) its position in your screen/world.
Greets
-
Re: [2008] Can I add a TCPClient Component
ok, first in the above code we did
Code:
Private Sub DoListen()
Dim incomingClient As System.Net.Sockets.TcpClient
Do
incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
Dim connClient As New ConnectedClient(incomingClient) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
' clients.Add(New ConnectedClient(incomingClient)) 'Adds the connected client to the list of connected clients.
clients.Add(connClient) 'Adds the connected client to the list of connected clients.
AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
Loop
End Sub
to add the new client ... should we remove it from here since we're going to add it in the MessageRecieved?
could u tell me how to create a string variable for holding the username in the ConnectedClient class, and create a string property for it...
thanks
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
ok, first in the above code we did
Code:
Private Sub DoListen()
Dim incomingClient As System.Net.Sockets.TcpClient
Do
incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
Dim connClient As New ConnectedClient(incomingClient) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
' clients.Add(New ConnectedClient(incomingClient)) 'Adds the connected client to the list of connected clients.
clients.Add(connClient) 'Adds the connected client to the list of connected clients.
AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
Loop
End Sub
to add the new client ... should we remove it from here since we're going to add it in the MessageRecieved?
could u tell me how to create a string variable for holding the username in the ConnectedClient class, and create a string property for it...
thanks
No we shouldnt remove it from that collection. Keep that method as it is:)
I'll edit the original code in my above post. Watch it closely;)
EDIT: There, take a look at the code for the ConnectedClient class, specificly at the mUsername variable and the Username property.
-
Re: [2008] Can I add a TCPClient Component
Excelent!
So now, each time a new client connects to my server, its username will be added to the listbox lbClients
How to send a msg to a specific Client (the one which is selected in the list box?)
thanks
-
Re: [2008] Can I add a TCPClient Component
@perito
Can You Post Your Full Code That is Working For You Now
I am also interested
-
Re: [2008] Can I add a TCPClient Component
@killer7k
sure Ill post the code when I finish the program
although this is pretty much it
http://www.vbforums.com/showpost.php...2&postcount=14
anyway, to all moderators and admins
PLEASE could you make this topic sticky or add it to the tut sections
u cant edit it if u want, but I kept searching for 4 days before atheist started helping me. Before his help, I couldnt find anything, everything on the web is 100x more complicated.
If anyone could turn this thread to a tut, that would be great !!
Please give credits to Atheist if u do so.
Thanks
@Atheist
could u plz reply to my previous question?
-
Re: [2008] Can I add a TCPClient Component
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
Excelent!
So now, each time a new client connects to my server, its username will be added to the listbox lbClients
How to send a msg to a specific Client (the one which is selected in the list box?)
thanks
You retrieve the selected username by using the SelectedItem property of the listbox (it returns an Object so it needs to be converted to a string).
You use the GetClientByName function to get the ConnectedClient instance connected to the username. Once you have it, call its SendMessage method.
-
Re: [2008] Can I add a TCPClient Component
OK, it worked gr8
Now how to figure out if a client disconnected from my server?
thx
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
OK, it worked gr8
Now how to figure out if a client disconnected from my server?
thx
The ideal thing is to have the client send a message whenever it closes down. When the server receives this message it should simply remove him from the list of connected clients.
However, if the client closes because of the system crashing or something of the sort, sending a message is obviously not possible. We will solve this by adding some nifty code when the exception occures in the doRead subroutine. But in order to do this we will need to change the ConnectedClients constructor, I'm going to update the code again..
Edit: There now I've edited the code.
Notice the new constructor in the ConnectedClient class, it takes one more argument, an the instance of Form1.
So upon creating a new ConnectedClient class, (on the doListen subroutine) we pass it like so: New ConnectedClass(incomingClient, Me)
This is because we want to call the new subroutine 'removeClient' from within ConnectedClass, like you can see being done in the doRead subroutine.
I hope this isnt too confusing for you :)
-
Re: [2008] Can I add a TCPClient Component
ok.. Im trying to remove the client name from lbClient
I have this code
Code:
Public Sub removeClient(ByVal client As ConnectedClient, ByVal ClientName As String)
If clients.Contains(client) Then
clients.Remove(client)
For x = 0 To lbClients.Items.Count - 1
If lbClients.Items.Item(x) = ClientName Then lbClients.Items.Remove(lbClients.Items.Item(x))
Next
End If
End Sub
as u see I created ClientName as string in the argument, but I donno how to add it to the declaration in the class
Code:
mParentForm.removeClient(Me)
must be changed and I must add something, what is it?
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
ok.. Im trying to remove the client name from lbClient
I have this code
Code:
Public Sub removeClient(ByVal client As ConnectedClient, ByVal ClientName As String)
If clients.Contains(client) Then
clients.Remove(client)
For x = 0 To lbClients.Items.Count - 1
If lbClients.Items.Item(x) = ClientName Then lbClients.Items.Remove(lbClients.Items.Item(x))
Next
End If
End Sub
as u see I created ClientName as string in the argument, but I donno how to add it to the declaration in the class
Code:
mParentForm.removeClient(Me)
must be changed and I must add something, what is it?
You can actually get rid of the Clientname argument, sending the client itself is sufficient, because you can then use Client.Username to get its name.
-
Re: [2008] Can I add a TCPClient Component
hmmm
The code is complete ?
I cant think of anything to add/change? :P
Do you think we should improve more, or is this enough? :D
The thread is resolved thanks to Atheist :))
-
Re: [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
hmmm
The code is complete ?
I cant think of anything to add/change? :P
Do you think we should improve more, or is this enough? :D
The thread is resolved thanks to Atheist :))
Good to hear its all working for you now:)
If everything is working as it should then you shouldnt change it. But if you need to adjust something in the future its very simple. Thats the advantage of learning how to use the System.Net.Socket classes instead of downloading ready-to-use components, its very versatile.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
ok one more question,
if I want to send small files (jpg lets say) from the server to client or back.
will i have to change all the code? is this a new program? or can I add some things?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by perito
ok one more question,
if I want to send small files (jpg lets say) from the server to client or back.
will i have to change all the code? is this a new program? or can I add some things?
hmm I've never tried to be honest, but it may require you to write to the stream using a System.Io.BinaryWriter instead of a System.IO.StreamWriter. And read from it using a System.IO.BinaryReader. I'll try to whip up some examples of that aswell.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
I have another question,
if I want to connect to an IRC Channel
is this code useful? or is it a tottally different code? how can I connect to IRC channels?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Go to mirc.com and look around they have a link to RFC's that detail the IRC client, server and other protocols. The code Atheist has provided for the client is sufficient but there is an enormous amount of coding that will need to be done if you want to correctly make a properly functioning IRC client. Also some of the code will obviously need to be changed to deal with the IRC protocols.
Atheist... I know a while ago we went over this whole tcp/sockets thing and u showed me collecting the clients in Hashtable but now i see you have used a List (Of ConnectedClients) - Which is better to use?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by ^^vampire^^
....Atheist... I know a while ago we went over this whole tcp/sockets thing and u showed me collecting the clients in Hashtable but now i see you have used a List (Of ConnectedClients) - Which is better to use?
A Hashtable is a collection of value/key pairs, meaning that when you add a client to it, you add its key (preferably the clients username) at the same time, so that the client object and the string key is added to the hashtable as a pair. You can then retrieve a client from it by specifying its username.
VB.Net Code:
Dim clientCollection As New HashTable
clientCollection.Add("This is a username", clientObject)
A List(Of T) is simpler, because you can not give the clients a key upon adding them. In the above example I've chosen to give each client a UserName property instead, and create my own GetClientByName function.
You can of course use which one you'd like, but I prefer the List(Of T) way.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
How would you list all servers on client side? Also, if you block the connection with firewall the program throws an error on server side once pressing the Listen button.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by kaisellgren
How would you list all servers on client side? Also, if you block the connection with firewall the program throws an error on server side once pressing the Listen button.
1. You can not list all servers without having a "master server" to keep track of the servers.
2. Thats why you should place all connection attempts in Try-Catch blocks.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by Atheist
1. You can not list all servers without having a "master server" to keep track of the servers.
2. Thats why you should place all connection attempts in Try-Catch blocks.
So all games like Counter-Strike have their servers oin a global master server? How does this sound:
1) When server is created, the server sends http request to www.master.com/addserver.php?ip=xxxx
2) When client window opens it sends http request to www.master.com/getservers.php and then it lists all IPs.
3) When server closes it sends http request to www.master.com/removeserver.php?ip=xxxx
Sounds good?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by kaisellgren
So all games like Counter-Strike have their servers oin a global master server?
Yeah, one or more master servers.
Quote:
Originally Posted by kaisellgren
Yeah that will work, except for the fact that anyone can use their browser and remove/add servers just to ruin the "system".
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
This isn't working :(
Code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
listener.Start() 'Start listening.
listenThread = New System.Threading.Thread(AddressOf DoListen) 'This thread will run the doListen method
listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
listenThread.Start() 'Start executing doListen on the worker thread.
Catch ex As Exception
Timer1.Enabled = False
Timer1.Interval = 5000
Timer1.Enabled = True
Exit Sub
End Try
End Sub
I have the same code in initial button press.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by kaisellgren
This isn't working :(
Code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
listener.Start() 'Start listening.
listenThread = New System.Threading.Thread(AddressOf DoListen) 'This thread will run the doListen method
listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
listenThread.Start() 'Start executing doListen on the worker thread.
Catch ex As Exception
Timer1.Enabled = False
Timer1.Interval = 5000
Timer1.Enabled = True
Exit Sub
End Try
End Sub
I have the same code in initial button press.
How come?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Ooh now it's working. Cool. All problems seem to be solved now :)
Now I need to figure out how to send http requests and how to get responses back.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Okay everything is working great except I have slight problems...
Code:
Error 3 'GetStream' is not a member of 'Chatter.Client'. C:\Documents and Settings\Kai\My Documents\Visual Studio 2008\Projects\Chatter\Chatter\Private.vb 9 38 Chatter
This is the error I keep getting.
I have a main form which is the client. In client I have a button "Open private chat window" which opens a private chat window. I have a private.vb form similar to my main chat window. The only problem is the above, my private.vb seems not to be able to use the connection code anymore, so:
How to make a new form/window to use existing connection used by main.vb?
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Thanks for the excellent code snippets, this thread got me quite far.
However, i have a problem: I am transfering strings between the client and the server (both ways), and those messages then get interpreted. When things happen/events fire at roughly the same time (i guess its because of that), the messages get corrupted and mixed up. Is there a way to rewrite the SendMessage method so, that i can be sure the string gets sent and recieved completly and nothing gets in between?
Another question: i am sending lots of values of type double. The way i do it now, i convert the double to a string, use the SendMessage method from the example in this thread, and on the other end i am converting the string back to a double. There are a lot of conversions going on, is there a more efficient way of doing this with sockets?
Any hints appreciated,
P.
-
Re: [RESOLVED] [2008] Can I add a TCPClient Component
Quote:
Originally Posted by pippi
Thanks for the excellent code snippets, this thread got me quite far.
However, i have a problem: I am transfering strings between the client and the server (both ways), and those messages then get interpreted. When things happen/events fire at roughly the same time (i guess its because of that), the messages get corrupted and mixed up. Is there a way to rewrite the SendMessage method so, that i can be sure the string gets sent and recieved completly and nothing gets in between?
Hmm. I've never had this happen to me, are you calling the Flush() method after each string being sent?
Have you made any other modifications or is the code on the first page of this thread basically what you have?
Edit: Are you saying that one clients message is mixed with another clients message? Or are two messages from the same client mixed together?
Quote:
Originally Posted by pippi
Another question: i am sending lots of values of type double. The way i do it now, i convert the double to a string, use the SendMessage method from the example in this thread, and on the other end i am converting the string back to a double. There are a lot of conversions going on, is there a more efficient way of doing this with sockets?
Any hints appreciated,
P.
I've never tried any of this so Im not 100% sure of how to go about it.
There's an overload of the StreamWriters Write method that'll let you write a double value directly to the stream. If you're only sending Doubles on the stream, you could modify the receiving end to only read 8 bytes at a time ( 1 double = 8 bytes), if you're sending doubles OR strings depending on the situation, it gets a bit more tricky. You'd have to add something like a header to your data before you send it that tells the receiving end what type of data its getting.
You'd have to modify the receiving end to