|
-
Apr 28th, 2011, 03:58 PM
#1
Thread Starter
Member
chat app over internet
Hi VB users
i have vb2010 express and fancy having a go at makeing a simple over internet chat application but i am a beginner at all this.
Would anybody be able to give me any pointers as i dont even know where to start.
all i have at min is a form with
1x read only textbox
1x textbox
1x button
and now from that i am lost as i never done anything with networks.
any help would be appreciated.
thanks
-
Apr 28th, 2011, 04:35 PM
#2
Banned
Re: chat app over internet
1st way :install c4f (it's for vb.net) then vb will have chat control in it's toolbox
2nd way :
TCP CHAT
client :
'5 textboxes txtIP, txtPort, txtUsername, txtMain, txtSend
'btnconnect,btnsend,btndisconnect
Code:
Public Class frmMainClient
Private client As System.Net.Sockets.TcpClient
Private Const BYTES_TO_READ As Integer = 255
Private readBuffer(BYTES_TO_READ) As Byte
Private Delegate Sub WriteText(ByVal text As String)
Private Sub BtnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnConnect.Click
If txtIP.Text = "" Or txtPort.Text = "" Or txtUserName.Text = "" Or IsNumeric(txtPort.Text) = False Or txtUserName.Text.IndexOf("|") >= 0 Then MsgBox("Fill text boxes properly") : Exit Sub
client = New System.Net.Sockets.TcpClient(txtIP.Text, txtPort.Text)
client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf DoRead, Nothing)
SendMessage("/CONNECT|" & txtUserName.Text)
txtUserName.Enabled = False
BtnSend.Enabled = True
BtnConnect.Enabled = False
txtSend.Enabled = True
txtIP.Enabled = False
txtPort.Enabled = False
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)
Select Case message
Case "/Connected"
ConnectionStatus("Client : Connected")
Case Else
WriteToMainText(message & vbCrLf)
End Select
End Sub
Private Sub ConnectionStatus(ByVal Message As String)
If Me.InvokeRequired Then
Me.Invoke(New WriteText(AddressOf ConnectionStatus), Message)
Else
Me.Text = "Client : Connected"
BtnDisconnect.Visible = True
BtnConnect.Height = 36
BtnConnect.Top = 9
End If
End Sub
Private Sub WriteToMainText(ByVal Message As String)
If txtMain.InvokeRequired Then
Me.Invoke(New WriteText(AddressOf WriteToMainText), Message)
Else
txtMain.AppendText(Message)
txtMain.SelectionStart = txtMain.Text.Length
End If
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
Private Sub frmMainClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BtnDisconnect.Visible = False
txtMain.ReadOnly = True
BtnSend.Enabled = False
txtSend.Enabled = False
End Sub
Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
SendMessage(txtUserName.Text & ": " & txtSend.Text)
WriteToMainText(txtUserName.Text & ": " & txtSend.Text & vbCrLf)
txtSend.Text = ""
End Sub
Private Sub BtnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDisconnect.Click
SendMessage("/DISCONNECT|" & txtUserName.Text)
BtnConnect.Enabled = True
BtnDisconnect.Visible = False
txtUserName.Enabled = True
BtnSend.Enabled = False
txtSend.Enabled = False
txtIP.Enabled = True
txtPort.Enabled = True
Me.Text = "Client"
End Sub
Private Sub txtSend_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSend.Enter
Me.AcceptButton = BtnSend
End Sub
End Class
-
Apr 28th, 2011, 04:36 PM
#3
Banned
Re: chat app over internet
server :
'We have
'4 textboxes txtSend, txtUsername, txtPort, txtMain (txtMain is multiline and readonly)
'lblConnection
'btnListen, btnSend, btnSendAll
'listbox lbClient
-
Apr 28th, 2011, 04:36 PM
#4
Banned
Re: chat app over internet
Code:
Public Class frmMainServer
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 Delegate Sub StringDelegate(ByVal text As String)
Private Sub frmMainServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'lblRemoveClient.Visible = False
txtMain.ReadOnly = True
txtSend.Enabled = False
BtnSend.Enabled = False
btnSendAll.Enabled = False
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) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
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(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
Public Sub removeClient(ByVal client As ConnectedClient)
If clients.Contains(client) Then
clients.Remove(client)
For x = 0 To lbClients.Items.Count - 1
If lbClients.Items.Item(x) = client.Username Then RemoveClientFromListBox(x) : Exit For
Next
End If
End Sub
Private Sub RemoveClientFromListBox(ByVal IndexOfClient As String)
If lbClients.InvokeRequired Then
Me.Invoke(New StringDelegate(AddressOf RemoveClientFromListBox), IndexOfClient)
Else
lbClients.Items.Remove(lbClients.Items.Item(Val(IndexOfClient)))
End If
End Sub
Private Sub BtnListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnListen.Click
If txtPort.Text = "" Or txtUserName.Text = "" Or IsNumeric(txtPort.Text) = False Or txtUserName.Text.IndexOf("|") >= 0 Then MsgBox("Fill text boxes properly") : Exit Sub
listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, txtPort.Text) '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.
txtPort.Enabled = False
BtnListen.Enabled = False
txtUserName.Enabled = False
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.
' 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
Dim data() As String = Message.Split("|"c)
Select Case data(0)
Case "/CONNECT"
If GetClientByName(data(1)) Is Nothing Then
sender.Username = data(1)
AddClientToListBox(data(1))
End If
SetConnectionLabelText("Connected")
sender.SendMessage("/Connected")
Case "/DISCONNECT"
removeClient(sender)
Case Else
WriteToMainText(Message & vbCrLf)
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
Return Nothing
End Function
Private Sub AddClientToListBox(ByVal ClientName As String)
If lbClients.InvokeRequired Then
Me.Invoke(New StringDelegate(AddressOf AddClientToListBox), ClientName)
Else
lbClients.Items.Add(ClientName)
If (lbClients.SelectedIndex < 0) And (lbClients.Items.Count > 0) Then lbClients.SelectedIndex = 0
End If
End Sub
Private Sub WriteToMainText(ByVal Message As String)
If txtMain.InvokeRequired Then
Me.Invoke(New StringDelegate(AddressOf WriteToMainText), Message)
Else
' Dim Usr As String
' Usr = Mid(Message, 1, Message.IndexOf("|"))
txtMain.Text = txtMain.Text & Message
txtMain.SelectionStart = txtMain.Text.Length
End If
End Sub
Private Sub SetConnectionLabelText(ByVal text As String)
If Me.LblConnection.InvokeRequired Then
Me.Invoke(New StringDelegate(AddressOf SetConnectionLabelText), text)
Else
Me.LblConnection.Text = text
BtnListen.Enabled = False
BtnSend.Enabled = True
btnSendAll.Enabled = True
txtSend.Enabled = True
End If
End Sub
Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
If txtSend.Text <> "" And lbClients.SelectedIndex >= 0 Then
Dim cc As ConnectedClient
cc = GetClientByName(Convert.ToString(lbClients.SelectedItem))
cc.SendMessage(txtUserName.Text & ": " & txtSend.Text)
WriteToMainText(txtUserName.Text & ": " & txtSend.Text & vbCrLf)
txtSend.Text = ""
End If
End Sub
Private Sub btnSendAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendAll.Click
If txtSend.Text <> "" Then
For Each cc As ConnectedClient In clients
cc.SendMessage(txtUserName.Text & ": " & txtSend.Text)
WriteToMainText(txtUserName.Text & ": " & txtSend.Text & vbCrLf)
Next
txtSend.Text = ""
End If
End Sub
Private Sub txtSend_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSend.Enter
Me.AcceptButton = BtnSend
End Sub
End Class
Public Class ConnectedClient
Private mClient As System.Net.Sockets.TcpClient
Private Const BYTES_TO_READ As Integer = 255
Private readBuffer(BYTES_TO_READ) As Byte
Private mUsername As String
Private mParentForm As frmMainServer
Public Event dataReceived(ByVal sender As ConnectedClient, ByVal message As String)
Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As frmMainServer)
mParentForm = parentForm
mClient = client
mClient.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'This will start reading from the stream between this server and the connected client.
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(ByVal ar As System.IAsyncResult)
Dim totalRead As Integer
Try
totalRead = mClient.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
Catch ex As Exception
mParentForm.removeClient(Me)
Exit Sub
'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)
RaiseEvent dataReceived(Me, receivedString)
End If
Try
mClient.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
Public Sub SendMessage(ByVal msg As String)
Dim sw As IO.StreamWriter
Try
sw = New IO.StreamWriter(mClient.GetStream) 'Create a new streamwriter that will be writing directly to the networkstream.
sw.Write(msg)
sw.Flush()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class
-
Apr 29th, 2011, 06:17 AM
#5
Thread Starter
Member
Re: chat app over internet
Very Nice Moti Barski
this is really good however i am testing it out now and am trying to have a 3way chat but only the user on the server form can see and reply to both of us, Yet the client forms can only see what is replied from the server and not the other client.??
I have tried looking into the code to see where i could possably change it to work. But as you are aware i am not to good at it yet lol
Do you have any Ideas ?
Thanks
-
Apr 29th, 2011, 10:52 AM
#6
Banned
Re: chat app over internet
the code is quite fat.
for a 3way chat i think c4f will work, or if you are very lazy you can place a webbrowser control (from the toolbox) and make it surf to a url with a chat like facebook
-
Apr 29th, 2011, 11:15 AM
#7
Banned
Re: chat app over internet
4th way :
skype (voice over ip)
notes : install skype (voip software), when running skype is running, you signed in it
1 dl skype4com from http://developer.skype.com/accessories
2 extract the zip file (3 files : chm, dll,msm)
3 open vb.net, file, new, project, window application
4 from tool box add :
textbox name : txtCallee
3 radio buttons : radTel, ralCell, radSkype
textbox multiline = true
button btnCall
textbox name: txtMsg
button btnSend
timer name : ChatTimer, true, interval 1000
5 project, add reference, browse , skype4com.dll
6 source code :
global vars : (add below class (after right click form, view code))
Dim oSkype As SKYPE4COMLib.Skype = New SKYPE4COMLib.Skype
Dim oCall As SKYPE4COMLib.Call
Dim oChat As SKYPE4COMLib.Chat
Code:
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If oSkype.Client.IsRunning = False Then
MsgBox("Skype must be running!")
End
End If
Try
If oSkype.CurrentUserStatus = SKYPE4COMLib.TUserStatus.cusOffline Then
MsgBox("Your Skype account must be online!")
End
End If
Catch ex As Exception
MsgBox("Your Skype account must be online!")
End Try
End Sub
Public Function parseTelNum(ByVal input As String, ByVal defaultIntl As String, ByVal defaultArea As String)
Dim result As String
result = input.Replace("-", " ")
If result.StartsWith("0") Then
Return "+" & defaultIntl & result.Substring(1)
ElseIf result.StartsWith("+") Then
Return result
Else
Return "+" & defaultIntl & defaultArea & result
End If
End Function
Private Sub btnCall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCall.Click
If btnCall.Text = "Call" Then
If txtCallee.Text = " " Then
Exit Sub
End If
If radTel.Checked = True Then
Try
oCall = oSkype.PlaceCall(parseTelNum(txtCallee.Text, "972", "2"))
btnCall.Text = "Hang up"
Catch ex As Exception
MsgBox("Couldn't place the call." & vbCrLf & "Please make sure the input you entered is valid!")
End Try
ElseIf radCell.Checked = True Then
oCall = oSkype.PlaceCall(parseTelNum(txtCallee.Text, "972", "52"))
Else
oCall = oSkype.PlaceCall(txtCallee.Text)
Else
oCall.Finish()
btnCall.Text = "Call"
End If
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If txtCallee.Text = " " Or txtMsg.Text = " " Then
Exit Sub
End If
If radTel.Checked = True Then
Try
oSkype.SendSms(parseTelNum(txtCallee.Text, "972", "2"), txtMsg.Text)
txtMsg.Text = ""
Catch ex As Exception
MsgBox("Coudn't send the SMS." & vbCrLf & "Please make sure the input you entered is valid!")
End Try
ElseIf radCell.Checked = True Then
oSkype.SendSms(parseTelNum(txtCallee.Text, "972", "52"), txtMsg.Text)
Else
oSkype.SendMessage(txtCallee.Text, txtMsg.Text)
MsgBox("Couldn't sent the message." & vbCrLf & "Please make sure the input you entered is valid!")
End Sub
Private Sub ChatTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChatTimer.Tick
txtChat.Text = ""
If txtCallee.Text <> "" Then
oChat = oSkype.CreateChatWith(txtCallee.Text)
Try
Dim temp = oChat.Messages
Catch ex As Exception
txtChat.Text = "No such username or no chat available." & vbCrLf & ex.ToString
Exit Sub
End Try
For Each oMsg As SKYPE4COMLib.ChatMessage In oChat.Messages
If Not oMsg.Body.ToString.StartsWith("<pa") And oMsg.Body.ToString <> "" Then
txtChat.Text = txtChat.Text & vbCrLf & oMsg.Sender.FullName & ": " & oMsg.Body
End If
Next
oSkype.ResetCache()
End If
End Sub
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
|