-
Jan 1st, 2008, 01:44 PM
#1
Thread Starter
Addicted Member
[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?
-
Jan 1st, 2008, 01:53 PM
#2
Member
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?
-
Jan 1st, 2008, 02:13 PM
#3
Thread Starter
Addicted Member
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.
-
Jan 1st, 2008, 02:19 PM
#4
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.
-
Jan 1st, 2008, 02:43 PM
#5
Thread Starter
Addicted Member
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
-
Jan 1st, 2008, 02:58 PM
#6
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.
-
Jan 1st, 2008, 06:07 PM
#7
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.
-
Jan 2nd, 2008, 05:27 AM
#8
Thread Starter
Addicted Member
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?
-
Jan 2nd, 2008, 06:26 AM
#9
Frenzied Member
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.
-
Jan 2nd, 2008, 06:29 AM
#10
Lively Member
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
-
Jan 2nd, 2008, 11:53 AM
#11
Re: [2008] Can I add a TCPClient Component
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.
-
Jan 2nd, 2008, 11:55 AM
#12
Re: [2008] Can I add a TCPClient Component
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.
-
Jan 2nd, 2008, 11:58 AM
#13
Thread Starter
Addicted Member
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..
-
Jan 2nd, 2008, 12:49 PM
#14
Re: [2008] Can I add a TCPClient Component
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.
Last edited by Atheist; Apr 11th, 2009 at 07:23 AM.
-
Jan 2nd, 2008, 01:19 PM
#15
Thread Starter
Addicted Member
Re: [2008] Can I add a TCPClient Component
thanks a million
I will check this code and reply asap
thanks again
-
Jan 2nd, 2008, 02:40 PM
#16
Thread Starter
Addicted Member
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
-
Jan 2nd, 2008, 02:55 PM
#17
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.
Last edited by Atheist; Jan 2nd, 2008 at 03:29 PM.
-
Jan 3rd, 2008, 05:34 AM
#18
Thread Starter
Addicted Member
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
-
Jan 3rd, 2008, 06:04 AM
#19
Frenzied Member
Re: [2008] Can I add a TCPClient Component
Elaborate more? He just told you exactly what to do. What are you having problems with?
-
Jan 3rd, 2008, 06:54 AM
#20
Thread Starter
Addicted Member
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
-
Jan 3rd, 2008, 10:57 AM
#21
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.
-
Jan 3rd, 2008, 11:30 AM
#22
Thread Starter
Addicted Member
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?
Last edited by perito; Jan 3rd, 2008 at 11:33 AM.
-
Jan 3rd, 2008, 11:39 AM
#23
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..
-
Jan 3rd, 2008, 11:59 AM
#24
Re: [2008] Can I add a TCPClient Component
There, I've edited the code to handle incoming messages on the client side.
-
Jan 3rd, 2008, 12:16 PM
#25
Thread Starter
Addicted Member
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?
-
Jan 3rd, 2008, 12:18 PM
#26
Re: [2008] Can I add a TCPClient Component
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.
-
Jan 3rd, 2008, 12:26 PM
#27
Thread Starter
Addicted Member
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
-
Jan 3rd, 2008, 12:36 PM
#28
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.
-
Jan 3rd, 2008, 12:55 PM
#29
Thread Starter
Addicted Member
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?
-
Jan 3rd, 2008, 01:12 PM
#30
Re: [2008] Can I add a TCPClient Component
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.
-
Jan 3rd, 2008, 01:24 PM
#31
Lively Member
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
-
Jan 3rd, 2008, 01:29 PM
#32
Thread Starter
Addicted Member
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
-
Jan 3rd, 2008, 01:37 PM
#33
Re: [2008] Can I add a TCPClient Component
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.
Last edited by Atheist; Jan 3rd, 2008 at 01:40 PM.
-
Jan 3rd, 2008, 03:09 PM
#34
Thread Starter
Addicted Member
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
-
Jan 3rd, 2008, 03:24 PM
#35
Fanatic Member
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
-
Jan 3rd, 2008, 03:43 PM
#36
Thread Starter
Addicted Member
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?
-
Jan 3rd, 2008, 03:57 PM
#37
Fanatic Member
Re: [2008] Can I add a TCPClient Component
-
Jan 3rd, 2008, 05:31 PM
#38
Re: [2008] Can I add a TCPClient Component
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.
-
Jan 4th, 2008, 04:20 AM
#39
Thread Starter
Addicted Member
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
-
Jan 4th, 2008, 08:56 AM
#40
Re: [2008] Can I add a TCPClient Component
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
Last edited by Atheist; Jan 4th, 2008 at 09:10 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|