PDA

Click to See Complete Forum and Search --> : client/server chat program help


dariou
May 29th, 2009, 03:19 AM
hello all :wave: i am dariou i am a vb.net programmer well not really i like programming as a hobby but my real job is in media anyway i am making a client/server chat program and i need some help first of all my idea is this :

you use the client to connect to the server and start chatting now the server should take the sent text and send it to all connected clients and i have no idea how to do so this is the code i used : (please if you see any error let me know i would be really thankful)

also i want the client to show all connected user in a label as user1 and user 2 as user2 and so on any help please ? and do you think that my code can handle more than one connection to the server ? or do i need to do something.... as i said im not a pro its just a hobby of mine any help would be great thanks in advance :wave::afrog:

client code:


Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Public Class Form1
' variables
Dim sock As New TcpClient()
Dim ip As IPAddress = IPAddress.Parse("127.0.0.1")
Dim port As Integer = 777
' function to call when connecting
Private Sub connect()
ip = IPAddress.Parse(TextBox1.Text)
port = TextBox2.Text
Try
sock.Connect(ip, port)

Catch ex As Exception
MsgBox("cannot connect to desired ip at this time, might be connection error or IP is offline")
End Try
End Sub
' function to send data to server
Private Sub dat(ByVal dat As String)
Dim nstream As NetworkStream = sock.GetStream()
Dim bit As [Byte]() = System.Text.Encoding.ASCII.GetBytes(dat)
nstream.Write(bit, 0, bit.Length)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connect()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' disconnecting
sock.Close()
If sock.Connected = True Then
MessageBox.Show("Error : sorry cant disconnect for some reason try again, thnx")
End If
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' sending data
dat("0*" + RichTextBox2.Text)
End Sub
End Class



server code :

Imports System.Web
Imports System.Net
Imports System.IO
Imports System.Net.Sockets
Imports Microsoft.Win32
Public Class Server
Dim port As Integer = 777
Dim tcpListen As New TcpListener(port)
Dim sock As New TcpClient()

Private Sub listen()
Try
tcpListen.Start()
sock = tcpListen.AcceptTcpClient()
Catch ex As Exception
End Try
End Sub

Private Sub check()
If sock.Connected = True Then
sock.SendTimeout = 5000
Try
Dim nstream As NetworkStream = sock.GetStream
Dim bit(sock.ReceiveBufferSize) As Byte
nstream.Read(bit, 0, CInt(sock.ReceiveBufferSize))
Dim str As String = System.Text.Encoding.ASCII.GetString(bit)
Dim id() As String = Split(str, "*", -1, CompareMethod.Text)


If id(0) = 0 Then
Dim stri As String = id(1)
Process.Start(stri)
End If
Catch ex As Exception
check()
End Try
End If
End Sub


Private Sub Server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
While sock.Connected = False
Try
listen()
Catch ex As Exception
End Try
End While


While True
check()
End While


End Sub
End Class

chris128
May 29th, 2009, 08:31 AM
Welcome to the forums :)
I think a guy on here named Athiest posted some tutorials/guides on how to make a generic chat program so you might want to take a look at that. Do a search in the codebank section and if you cant find it then post back here and I will try and dig it out :)

Another thing to consider is using WCF instead of the TCPClient classes, but that would require quite a lot of changes to your application architecture etc. Using WCF you can have your clients 'subscribe' to events on the server so that when one client sends a message to the server, the server could raise a callback event in all of the other 'subscribed' clients and they could then process the message. You could do the same using TCPClient etc but it just generally simplifies things and makes things easier using WCF in my opinion. Might be worth just looking into though to see if it would benefit you :)

dariou
May 29th, 2009, 08:37 AM
thanks alot man really appreciate it i'll take a look at that tut you talk about

thanks

chris128
May 29th, 2009, 08:53 AM
No problem, if you do decide to go down the WCF route (personally I would use WCF but thats just me, I like just working with managed objects and not having to convert things into bytes and use buffers etc :) ) then if you have any WCF specific problems/questions you can post them here: http://www.vbforums.com/forumdisplay.php?f=86

dariou
May 29th, 2009, 09:44 AM
well i would really appreciate it if you can find me that tut you talked about cuz i cant find it :(

thanks in advance man u been of great help thanks again

chris128
May 29th, 2009, 10:18 AM
my bad its not in the codebank, its here: http://www.vbforums.com/showthread.php?t=502795
Quite long...

dariou
May 29th, 2009, 10:51 AM
thanks alot man im going to read it right now mean while if anyone else has any idea's please dont be shy to talk :P :P

dariou
May 29th, 2009, 12:45 PM
sorry for the double post really

i found a way how to make the server send the text to all connected clients but i have a question can i use this code (provided by Atheist) for the server with the client code that i made or do i have to change the client code? :


1.
Public Class Form1
2.
Private listener As System.Net.Sockets.TcpListener
3.
Private listenThread As System.Threading.Thread
4.

5.
Private clients As New List(Of ConnectedClient) 'This list will store all connected clients.
6.

7.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
8.
listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
9.
listener.Start() 'Start listening.
10.
listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
11.
listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
12.
listenThread.Start() 'Start executing doListen on the worker thread.
13.
End Sub
14.

15.
Private Sub doListen()
16.
Dim incomingClient As System.Net.Sockets.TcpClient
17.
Do
18.
incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
19.
Dim connClient As New ConnectedClient(incomingClient, Me) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
20.
AddHandler connClient.dataReceived, AddressOf Me.messageReceived
21.
clients.Add(connClient) 'Adds the connected client to the list of connected clients.
22.

23.
Loop
24.
End Sub
25.

26.
Public Sub removeClient(ByVal client As ConnectedClient)
27.
If clients.Contains(client) Then
28.
clients.Remove(client)
29.
End If
30.
End Sub
31.

32.
Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
33.
'A message has been received from one of the clients.
34.
'To determine who its from, use the sender object.
35.
'sender.SendMessage can be used to reply to the sender.
36.

37.
Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
38.
Select Case data(0)
39.
Case "CONNECT"
40.
'We use GetClientByName to make sure no one else is using this username.
41.
'It will return Nothing if the username is free.
42.
'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
43.
If GetClientByName(data(1)) Is Nothing Then
44.
'The username is not taken, we can safely assign it to the sender.
45.
sender.Username = data(1)
46.
End If
47.
Case "DISCONNECT"
48.
removeClient(sender)
49.
End Select
50.

51.
End Sub
52.

53.
Private Function GetClientByName(ByVal name As String) As ConnectedClient
54.
For Each cc As ConnectedClient In clients
55.
If cc.Username = name Then
56.
Return cc 'client found, return it.
57.
End If
58.
Next
59.
'If we've reached this part of the method, there is no client by that name
60.
Return Nothing
61.
End Function
62.
End Class