Anda di halaman 1dari 34

LAPORAN MICROPROCESSOR DAN ANTARMUKA

Job 7
Text And Voice Chat

Disusun oleh :
Kelompok 1
1. Desyana S.P. (3.34.12.0.07)
2. Dwi Achiyari B. P. (3.34.12.0.09)
3. Evan Enza R. (3.34.12.0.10)
4. Sukirno (3.34.12.0.20)
IK-2A

PROGRAM STUDI TEKNIK INFORMATIKA


JURUSAN TEKNIK ELEKTRO
POLITEKNIK NEGERI SEMARANG
2013/2014
Kelompok 1 Job 7- Text and voice chat

Text And Voice Chat


I. TUJUAN
Setelah melakukan praktikum ini mahasiswa diharapkan mampu:
1. Membuat aplikasi chat text to text.
2. Membuat aplikasi chat text to voice / voice to text.
3. Membuat aplikasi chat voice to voice.

II. DASAR TEORI


Konsep TCP
TCP ( Transmission Control Protocol ) merupakan protocol transport yang andal
( reliable ), hal ini dikarenakan protokol TCP mempunyai mekanisme yang memastikan
packet dapat diterima oleh client. Pada saat TCP mengirimkan data ke penerima, TCP akan
memberikan state acknowledgement. Apabila state acknowledgement tidak diterima, maka
TCP akan secara otomatis mengirim ulang data dan menunggu dengan selang waktu tertentu
namun apabila dalam selang waktu tertentu TCP gagal mengirimkan data, maka koneksi
akan dihentikan.
TCP client dapat membangun koneksi yang disediakan oleh server, saling menukar data
melalui koneksi yang dibangun dan kemudian menghentikan koneksi. Sebagai protokol
jaringan yang andal, protokol ini bekerja berkelanjutan untuk menjamin pengiriman semua
data, dan sesuai dengan urutan pengirimannya. Sehingga kita tahu bahwa client menerima
tepat seperti yang kita kirim. Karena inilah aplikasi yang perlu mempertukarkan data dalam
volume besar biasanya menggunakan TCP.
Sebagai catatan, TCP tidak menjamin data akan diterima oleh si penerima apabila
koneksi tidak dimungkinkan terbangun ( misal: server sedang down, salah konfigurasi IP,
kabel tidak dibuat dengan baik, salah melakukan netmasking dll ), sebaliknya TCP dapat
menjamin pengiriman data ke si penerima apabila koneksi memang memungkinkan
terbangun dan memberikan pesan kesalahan ( koneksi terputus atau tidak menerima
acknowledgement ) kepada user apabila koneksi tidak memungkinkan dibangun.
TCP memiliki algoritma yang digunakan untuk memperkirakan round-trip time ( RTT )
yaitu waktu yang dibutuhkan pada saat pengiriman data antara client dan server. RTT yang
dihasilkan bersifat dinamis, sehingga TCP dapat memperkirakan berapa lama harus
2|Mikroprocessor dan Antarmuka
Kelompok 1 Job 7- Text and voice chat

menunggu acknowledgement pada koneksi yang dibangun. Sebagai contohnya, RTT yang
didapat dari LAN biasanya hanya dalam besaran milisecond sementara untuk WAN, RTT
bisa dalam besaran second. TCP selalu menghitung RTT dari koneksi yang dibangun secara
terus – menerus, hal ini dikarenakan RTT banyak dipengaruhi oleh keadaan traffic jaringan
yang selalu berubah – ubah setiap waktu.
TCP dapat mengurutkan setiap byte data yang dikirim. Sebagai contohnya, asumsikan
suatu aplikasi mengirimkan 2048 bytes data ke TCP socket, yang menyebabkan TCP akan
mengirim sebanyak 2 segment. Segment yang pertama mengirimkan data dengan urutan 1 –
1024 dan segment yang kedua akan mengirimkan data dengan urutan 1025 – 2048. Apabila
segment yang diterima tidak sesuai dengan segment yang dikirim, maka TCP si penerima
akan meminta pengiriman ulang 2 segment tersebut berdasarkan urutan yang benar sebelum
dikirim ke level aplikasi si penerima. Apabila TCP menerima duplikasi data dari pengirim
( misal network memperkirakan ada segment data yang hilang, sehingga meminta
pengiriman ulang, padahal segment data tersebut tidak benar – benar hilang dikarenakan
network overload), maka TCP dapat mendeteksi duplikasi data tersebut dan membuang data
yang tidak digunakan.
Pada saat suatu aplikasi socket melakukan koneksi, kita dapat melihat state – state yang
dialami oleh aplikasi socket tersebut. State – state yang dilakukan oleh TCP pada saat
melakukan koneksi yaitu :
1. LISTEN
2. SYN-SENT
3. SYN-RECEIVED
4. ESTABLISHED
5. FIN-WAIT-1
6. FIN-WAIT-2
7. CLOSE-WAIT
8. CLOSING
9. LAST-ACK
10. TIME-WAIT
11. CLOSED
LISTEN

3|Mikroprocessor dan Antarmuka


Kelompok 1 Job 7- Text and voice chat

menunggu connection request dari client. ( di set oleh TCP Server )


SYN-SENT
client telah mengirim paket SYN dan ACK ke TCP Server , kemudian client menunggu
paket SYN dan ACK balasan dari Server.
SYN-RECEIVED
menunggu dari TCP Client untuk mengembalikan state acknowledgment setelah mengirim
state acknowledgment ke TCP Client.
ESTABLISHED
Koneksi telah dibangun, client server siap untuk mengirim dan menerima data.
TIME-WAIT
merupakan waktu yang dibutuhkan untuk memastikan TCP menerima state acknowledgment
pada saat menghentikan koneksi.
State – state diatas dapat dilihat dengan menggunakan perintah netstat pada command line.

Konsep UDP
UDP ( User Datagram Protocol ) adalah transport layer yang tidak andal ( unreliable ),
connectionless dan merupakan kebalikan dari transport layer TCP. Dengan menggunakan
UDP, setiap aplikasi socket dapat mengirimkan paket – paket yang berupa datagram. Istilah
datagram diperuntukkan terhadap paket dengan koneksi yang tidak andal ( unreliable service
). Koneksi yang andal selalu memberikan keterangan apabila pengiriman data gagal,
sedangkan koneksi yang tidak andal tidak akan mengirimkan keterangan meski pengiriman
data gagal.
UDP tidak menjamin kevalidan data saat data sampai ke si penerima. Datagram yang
sampai mempunyai kemungkinan tidak sampai, rusak, duplikasi atau hilang tanpa diketahui
penyebabnya. Penggunaan UDP lebih tepat diperuntukkan untuk data – data kecil dengan
jumlah banyak. Dengan perilaku UDP yang tidak berusaha untuk mengecek apakah data
yang dikirim telah sampai atau tidak membuat UDP lebih cepat dan lebih efisien. Aplikasi –
aplikasi yang bersifat real time seringkali menggunakan UDP sebagai protokolnya, hal
tersebut dikarenakan paket yang hilang lebih bisa ditolerir daripada paket yang datang
terlambat ( contoh aplikasi realtime: Video Streaming ). Tidak seperti TCP, UDP juga

4|Mikroprocessor dan Antarmuka


Kelompok 1 Job 7- Text and voice chat

menyediakan jenis paket broadcast (mengirim paket ke local network) dan multicast
(mengirim paket ke semua subscriber).
Dalam UDP, client tidak membangun koneksi dengan server, melainkan client hanya
mengirim paket data ke server tanpa mengecek apakah server tersebut telah siap atau tidak.
Sama halnya dengan server tidak menerima koneksi dengan fungsi accept, namun server
hanya menjalankan perintah untuk menerima data, server akan terus menunggu sampai data
diterima.

III. ALAT DAN BAHAN


1. 1 buah laptop
2. Aplikasi Visual Studio 2010

IV. LANGKAH KERJA


1. Untuk membuat aplikasi chat, buka dahulu Visual Basic dan buat form baru.
2. Siapkan komponen yang diperlukan seperti berikut :
 MenuStrip
 PictureBox
 Label
 RichTextBox
 Button
 Timer
3. Kemudian atur form seperti berikut :

5|Mikroprocessor dan Antarmuka


Kelompok 1 Job 7- Text and voice chat

4. Agar aplikasi chat tersebut dapat dijalankan, terlebih dahulu buat kode programnya.
5. Terlebih dahulu masukkan library dan buat variable sebagai berikut :

Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Imports System
Imports System.Net.Dns
Imports System.Drawing.Bitmap
Imports CustomControls.IconComboBox
Imports UNOLibs.Net.ClientClass
Imports RapChatLib.RapChatLib

Public Class Form1

#Region "Declarations"

Dim Listener As New TcpListener(65535)


Dim Client As New TcpClient
Dim Message As String = ""
Dim Listener1 As New TcpListener(65534)

6|Mikroprocessor dan Antarmuka


Kelompok 1 Job 7- Text and voice chat

Dim Client1 As New TcpClient


Dim Message1 As String = ""
Dim IPAdd As String
Dim clnt As New UNOLibs.Net.ClientClass
Dim clnt2 As New UNOLibs.Net.ClientClass
Dim WithEvents server As UNOLibs.Net.ServerClass
Dim WithEvents server2 As UNOLibs.Net.ServerClass

#End Region

#Region "Form"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Me.Location = My.Settings.WindowPosition
Me.Size = My.Settings.WindowSize
txtSound.Text = My.Settings.Audio
txtName.Text = My.Settings.Username
PicClient.ImageLocation = My.Settings.DisplayPic
picMypic.ImageLocation = My.Settings.DisplayPic
frmSettings.chkSound.CheckState = My.Settings.ChkSound

txtSaveLoc.Text = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\"


server = New UNOLibs.Net.ServerClass(65533, True, txtSaveLoc.Text)
server2 = New UNOLibs.Net.ServerClass(65532, True, "C:\")
Dim ListThread As New Thread(New ThreadStart(AddressOf Listening)) 'Creates
the thread
ListThread.Start() 'Starts the thread

Dim shostname As String


shostname = System.Net.Dns.GetHostName
Console.WriteLine("Your Machine Name = " & shostname)
'Call Get IPAddress
Console.WriteLine("Your IP = " & GetIPAddress())
StatusStrip1.Text = ("My Computer: " & shostname & " - " & GetIPAddress())
NotifyIcon1.Visible = True
Dim me1 As New IconComboItem
Dim ico As New Icon(My.Application.Info.DirectoryPath & "\Users.ico")
me1.DisplayText = GetIPAddress()
me1.ItemImage = ico
cmbAddress.Items.Add(me1)
My.Application.SaveMySettingsOnExit = True
cmbAddress.SelectedIndex = 0
End Sub

Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
NotifyIcon1.Visible = False
End Sub

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Dim offlinestring As String = " Has gone Offline. You can No longer Message
This User."
If RichTextBox1.Text.Contains(offlinestring) Then
End
Else
txtmessage.Text = txtName.Text & " Has gone Offline. You can No longer
7|Mikroprocessor dan Antarmuka
Kelompok 1 Job 7- Text and voice chat

Message This User."


btnSend.PerformClick()

My.Settings.WindowPosition = Me.Location
My.Settings.WindowSize = Me.Size
My.Settings.Username = txtName.Text
My.Settings.DisplayPic = PicClient.ImageLocation
My.Settings.Audio = txtSound.Text
My.Settings.Save()

End If
End Sub

#End Region

#Region "Functions"

Public Shared Function GetIPAddress() As String


Dim oAddr As System.Net.IPAddress
Dim sAddr As String
With System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
oAddr = New System.Net.IPAddress(.AddressList(0).Address)
sAddr = oAddr.ToString
End With
GetIPAddress = sAddr
End Function

Private Sub Listening()


Listener.Start()
Listener1.Start()
End Sub

Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e


As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
Me.Show()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
If Listener.Pending = True Then
Message = ""
Client = Listener.AcceptTcpClient()

Dim Reader As New StreamReader(Client.GetStream())


While Reader.Peek > -1
Message = Message + Convert.ToChar(Reader.Read()).ToString
End While
RichTextBox1.ForeColor = Color.Black
RichTextBox1.Text += Message + vbCrLf

If frmSettings.chkSound.CheckState = CheckState.Unchecked Then


NotifyIcon1.BalloonTipTitle = ("New Message")
NotifyIcon1.BalloonTipText = Message
NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
frmMessage.Show()
frmMessage.lblMessage.Text = Message
lblStat.Text = ("Last Message Received At " &
My.Computer.Clock.LocalTime)
Else
My.Computer.Audio.Play(txtSound.Text)
NotifyIcon1.BalloonTipTitle = ("New Message")
8|Mikroprocessor dan Antarmuka
Kelompok 1 Job 7- Text and voice chat

NotifyIcon1.BalloonTipText = Message
NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
frmMessage.Show()
frmMessage.lblMessage.Text = Message
lblStat.Text = ("Last Message Received At " &
My.Computer.Clock.LocalTime)
End If

End If

If Listener1.Pending = True Then


Message1 = ""
Client1 = Listener1.AcceptTcpClient()

Dim Reader1 As New StreamReader(Client1.GetStream())


While Reader1.Peek > -1
Message1 = Message1 + Convert.ToChar(Reader1.Read()).ToString
End While
PicClient.Image = StringToBitmap(Message1)
End If
End Sub

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnSend.Click
If txtName.Text = "" Or cmbAddress.Text = "" Then
MessageBox.Show("All Fields must be Filled", "Error Sending Message",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
btnImage.PerformClick()
Try
Client = New TcpClient(cmbAddress.Text, 65535)

Dim Writer As New StreamWriter(Client.GetStream())


Writer.Write(txtName.Text & " Says: " & txtmessage.Text)
Writer.Flush()
RichTextBox1.Text += (txtName.Text & " Says: " & txtmessage.Text) +
vbCrLf
txtmessage.Text = ""
Catch ex As Exception
Console.WriteLine(ex)
Dim Errorresult As String = ex.Message
MessageBox.Show(Errorresult & vbCrLf & vbCrLf & "Please Review Client
Address", "Error Sending Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End If
End Sub

Private Sub txtmessage_TextChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles txtmessage.TextChanged
Dim imagepath As String = My.Application.Info.DirectoryPath & "\Message.png"
Dim img As Image = Image.FromFile(imagepath)
lblStat.Image = img
lblStat.Text = "Writing Message..."

If txtmessage.Text <> "" Then


btnClear.Enabled = True

9|Mikroprocessor dan Antarmuka


Kelompok 1 Job 7- Text and voice chat

btnSend.Enabled = True
Else
btnClear.Enabled = False
btnSend.Enabled = False
End If
End Sub

Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnConnect.Click
If cmbAddress.Text.Length < 4 Then
MessageBox.Show("Please Enter a Valid Address", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
btnConnect.Text = "Connecting"
Dim pingresult As String = My.Computer.Network.Ping(cmbAddress.Text)
If pingresult = "True" Then
btnConnect.Text = "Connected"
Else
btnConnect.Text = "Disconnected"
End If
End If

End Sub

Private Sub cmbAddress_TextChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmbAddress.TextChanged
btnConnect.Text = "Connect..."
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClear.Click
txtmessage.Text = ""
lblStat.Text = "Last Message Received At: "
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnImBrowse.Click
ofdImage.ShowDialog()
If ofdImage.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
picMypic.ImageLocation = ofdImage.FileName
PicClient.ImageLocation = ofdImage.FileName
Dim imgstr As String
Dim abyt As Byte()
Dim ms As New IO.MemoryStream
Dim bmp As New Bitmap(picMypic.ImageLocation)

bmp.Save(ms, Imaging.ImageFormat.Bmp)

abyt = ms.ToArray()
imgstr = System.Convert.ToBase64String(abyt)
TextBox1.Text = imgstr
PicClient.Image = picMypic.Image
Else
PicClient.ImageLocation = My.Application.Info.DirectoryPath &
"\Data\Users.png"
picMypic.ImageLocation = My.Application.Info.DirectoryPath &
"\Data\Users.png"

10 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

End If
End Sub

Public Function StringToBitmap(ByVal sImageData As String) As Bitmap


Try
Dim ms As New MemoryStream(Convert.FromBase64String(sImageData))
Dim bmp As Bitmap = Bitmap.FromStream(ms)
Return bmp
Catch ex As Exception
Return Nothing
End Try
End Function

Private Sub ImageButton2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ImageButton2.Click
btnConnect.PerformClick()
End Sub

Private Sub ImagebtnConnect_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ImageButton1.Click
cmbAddress.Text = ""
txtName.Text = ""
txtmessage.Text = ""
RichTextBox1.Text = ""
End Sub

Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Timer3.Tick

End Sub

Private Sub btnImage_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnImage.Click

clnt2.SendMessage(cmbAddress.Text, 65532, TextBox1.Text)


End Sub

Private Sub txtName_TextChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles txtName.TextChanged
Me.Text = ("Rapid Chat - " & txtName.Text)
End Sub

Private Sub HideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles HideToolStripMenuItem.Click
Me.Hide()
End Sub

Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
frmSettings.Show()
End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub

11 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnBrowse.Click
frmMyData.Show()
End Sub

Private Sub NetworkStatusToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles NetworkStatusToolStripMenuItem.Click
btnBrowse.PerformClicked()
End Sub

Private Sub txtmessage_Leave(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles txtmessage.Leave
lblStat.Text = "Last Message Received At:"
End Sub

Private Sub PicClient_DoubleClick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles PicClient.DoubleClick
frmNewAddress.Show()
End Sub

Private Sub FontToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles FontToolStripMenuItem.Click
fntFont.ShowDialog()
If DialogResult.OK Then
RichTextBox1.Font = fntFont.Font
End If
End Sub

Private Sub FileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles FileToolStripMenuItem.Click
SendFileToolStripMenuItem.PerformClick()
End Sub

Private Sub SendFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles SendFileToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()

If DialogResult.OK Then
RichTextBox1.Text += (txtName.Text & " Is Sending You a File...") +
vbCrLf
clnt.SendFiles(cmbAddress.Text, 65533, OpenFileDialog1.FileNames)
Else
Exit Sub
End If
End Sub

Private Sub BrowseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles BrowseToolStripMenuItem.Click
FolderBrowserDialog1.ShowDialog()
If DialogResult.OK Then
txtSaveLoc.Text = FolderBrowserDialog1.SelectedPath & "\"
server.IncomingPath = txtSaveLoc.Text
Else
txtSaveLoc.Text = My.Computer.FileSystem.SpecialDirectories.MyDocuments
End If
End Sub

Private Sub OnDiagnosticMessage(ByVal Args As String) Handles


server.DiagnosticMessage
RichTextBox1.Text += (txtName.Text & " - " & Args) + vbCrLf
My.Computer.Audio.Play(My.Application.Info.DirectoryPath &
12 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

"\Sounds\Notify.wav")
End Sub

Private Sub mnuCut_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles mnuCut.Click
RichTextBox1.Cut()
End Sub

Private Sub mnuCopy_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles mnuCopy.Click
RichTextBox1.Copy()
End Sub

Private Sub mnuSelectAll_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles mnuSelectAll.Click
RichTextBox1.SelectAll()
End Sub

Private Sub FontToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles FontToolStripMenuItem1.Click
FontToolStripMenuItem.PerformClick()
End Sub

Private Sub OnIncomingMessage(ByVal Args As UNOLibs.Net.ServerClass.InMessEvArgs)


Handles server2.IncomingMessage
PicClient.Image = StringToBitmap(Args.message)
End Sub

Private Sub FontColourToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles FontColourToolStripMenuItem.Click
clrFont.ShowDialog()
If DialogResult.OK Then
RichTextBox1.ForeColor = clrFont.Color
Else
RichTextBox1.ForeColor = Color.Black
End If
End Sub

Private Sub ExitToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles ExitToolStripMenuItem2.Click
End
End Sub

Private Sub ShowToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles ShowToolStripMenuItem1.Click
Me.Show()
End Sub

Private Sub SettingsToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles SettingsToolStripMenuItem1.Click
frmSettings.Show()
End Sub

Private Sub SettingsToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles SettingsToolStripMenuItem2.Click
frmSettings.Show()
End Sub

Private Sub ExitToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e


13 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

As System.EventArgs) Handles ExitToolStripMenuItem1.Click


End
End Sub

Private Sub RichTextBox1_MouseMove(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseMove
If RichTextBox1.SelectionLength > 0 Then
mnuCut.Enabled = True
mnuCopy.Enabled = True
cmsmCut.Enabled = True
cmsmCopy.Enabled = True
Else
mnuCut.Enabled = False
mnuCopy.Enabled = False
cmsmCut.Enabled = False
cmsmCopy.Enabled = False
End If
End Sub

Private Sub SelectAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles SelectAllToolStripMenuItem.Click
RichTextBox1.SelectAll()
End Sub

#End Region

#Region "Status"

Private Sub AwayToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles AwayToolStripMenuItem2.Click
txtmessage.Text = AwayToolStripMenuItem2.Tag
btnSend.PerformClick()
pnlStatus.Visible = True
lblStatus.Text = "Your Status is currently set to Away"
End Sub

Private Sub lnkOnline_LinkClicked(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkOnline.LinkClicked
txtmessage.Text = "I am currently Online"
btnSend.PerformClick()
pnlStatus.Visible = False
End Sub

Private Sub mnuBusy_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles mnuBusy.Click
txtmessage.Text = mnuBusy.Tag
btnSend.PerformClick()
pnlStatus.Visible = True
lblStatus.Text = "Your Status is currently set to Busy"
End Sub

Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnClose.Click
pnlStatus.Visible = False
End Sub

Private Sub mnuAppearOff_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles mnuAppearOff.Click
mnuAppearOff.Tag = txtName.Text & " Has gone Offline. You can No longer
Message This User."
txtmessage.Text = mnuAppearOff.Tag
14 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

btnSend.PerformClick()
pnlStatus.Visible = True
lblStatus.Text = "Your Status is currently set to Appear Offline"
End Sub

Private Sub OnlineToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e


As System.EventArgs) Handles OnlineToolStripMenuItem2.Click
txtmessage.Text = "I am currently Online"
btnSend.PerformClick()
pnlStatus.Visible = False
End Sub

#End Region

Private Sub AboutRapidChatToolStripMenuItem_Click(ByVal sender As System.Object,


ByVal e As System.EventArgs) Handles AboutRapidChatToolStripMenuItem.Click
Process.Start(My.Application.Info.DirectoryPath & "\About Rapid Chat\About
Rapid Chat.exe")
End Sub
End Class
6. Buat form message dengan tampilan seperti berikut :

7. Kemudian berikn kode program message sebagai berikut :


Public Class frmMessage

Dim max As Integer = Screen.GetWorkingArea(Me).Height - Me.Height


Dim x As New Integer
Dim y As Integer = Screen.GetWorkingArea(Me).Height
Dim i As Integer = 100

Private Sub frmMessage_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

PicMe.Image = Form1.PicClient.Image

x = Screen.GetWorkingArea(Me).Width
y = Screen.GetWorkingArea(Me).Height
Me.Location = New Point(x, y)
Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Timer1.Tick
x = Screen.GetWorkingArea(Me).Width - Me.Width
If y = max Then

15 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

Timer1.Enabled = False
Timer2.Enabled = True
Else
Me.Location = New Point(x, y)
y = y - 1
End If
End Sub

Private Sub GlassButton1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles GlassButton1.Click
Me.Close()
End Sub

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Timer2.Tick
If i = 30 Then
Me.Close()
Else
Me.Opacity = i
i = i - 1
End If
End Sub
End Class
8. Kemudian buat form mydata seperti berikut :

9. Kemudian masukkan kode program sebagai berikut :


Public Class frmMyData

Private Sub frmMyData_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
lblIP.Text = Form1.GetIPAddress
lblConnection.Text = My.Computer.Network.IsAvailable
End Sub

End Class
10. Buat form untuk new address dengan tampilan berikut :

11. Kemudian masukkan kode program sebagai berikut pada form tersebut :
16 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

Imports CustomControls.IconComboBox

Public Class frmNewAddress

Private Sub btnImBrowse_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnImBrowse.Click
Dim NewAdd As New IconComboItem
Dim ico As New Icon(My.Application.Info.DirectoryPath & "\Users.ico")
NewAdd.DisplayText = txtAddress.Text
NewAdd.ItemImage = ico
Form1.cmbAddress.Items.Add(NewAdd)
Me.Close()
End Sub

Private Sub GlassButton1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles GlassButton1.Click
Me.Close()
End Sub

End Class

12. Buat tampilan untuk form setting seperti berikut :

13. Kemudian pada form setting berikan kode berikut :


Public Class frmSettings

Private Sub btnImBrowse_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnImBrowse.Click
Form1.txtName.Text = txtName.Text
Form1.txtSound.Text = txtSound.Text
My.Settings.ChkSound = chkSound.CheckState
Form1.PicClient.ImageLocation = picDisplay.ImageLocation
17 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

Form1.picMypic.ImageLocation = picDisplay.ImageLocation
Form1.RichTextBox1.Font = New Font(cmbFont.Text, cmbSize.Text)
My.Settings.Save()
Me.Close()
End Sub

Private Sub GlassButton1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles GlassButton1.Click
Me.Close()
End Sub

Private Sub frmSettings_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
txtName.Text = Form1.txtName.Text
txtSound.Text = My.Application.Info.DirectoryPath & "\Sounds\Notify.wav"
ofdSound.InitialDirectory =
My.Computer.FileSystem.SpecialDirectories.MyDocuments
chkSound.CheckState = My.Settings.ChkSound

For Each font As FontFamily In FontFamily.Families


cmbFont.Items.Add(font.Name)
Next font

cmbFont.Text = Form1.RichTextBox1.Font.Name
cmbSize.Text = Form1.RichTextBox1.Font.Size

picDisplay.ImageLocation = Form1.PicClient.ImageLocation
txtPic.Text = Form1.PicClient.ImageLocation
End Sub

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnBrowse.Click
ofdSound.ShowDialog()
If DialogResult.OK Then
txtSound.Text = ofdSound.FileName
Else
txtSound.Text = My.Application.Info.DirectoryPath & "\Sounds\Notify.wav"
End If
End Sub

Private Sub btnPicBrowse_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnPicBrowse.Click
Form1.ofdImage.ShowDialog()
If DialogResult.OK Then
txtPic.Text = Form1.ofdImage.FileName
picDisplay.ImageLocation = Form1.ofdImage.FileName
End If
End Sub

Private Sub GlassButton2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles GlassButton2.Click
colFont.ShowDialog()
End Sub

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnAdd.Click
tvwBlockedUser.TopNode.Nodes.Add(txtblockUser.Text)
End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As

18 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

System.EventArgs) Handles btnRemove.Click


tvwBlockedUser.Nodes.RemoveAt(tvwBlockedUser.SelectedNode.Index)
End Sub
End Class

19 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

Uji Coba Aplikasi Chat


1. Hubungkan laptop ke dalam sebuah jaringan wifi dengan access point,seperti berikut :

2. Kemudian cek IP yang telah didapatkan,seperti berikut :

3. Buka aplikasi Chat seperti berikut :

20 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

4. Lihat menu pada aplikasi chat  Network Status :

5. Jika IP sudah didapatkan pada aplikasi chat, silahkan hubungkan ke user lain dengan
memasukkan IP pada komputer lain :

21 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

6. Berikut untuk mencoba komunikasi menggunakan chat :

VOICE CHAT
22 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

1. Buat tampilan form voice chat seperti berikut :

2. Toolbox yang digunakan


Properties Name Teks
Form Simpan_File Simpan File
Label  Label1  VOICE CHAT
 LblCallto  Call to
 LblName  Name
 Label6  Codec

Button  btnCall  Call


 btnEndCall  End Call
Combobox  Combobox_codec  cmbCodecs

3. Berikan kode program berikut :


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using g711audio;

namespace VoiceChat
{
public partial class VoiceChat : Form
{

23 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

private CaptureBufferDescription captureBufferDescription;


private AutoResetEvent autoResetEvent;
private Notify notify;
private WaveFormat waveFormat;
private Capture capture;
private int bufferSize;
private CaptureBuffer captureBuffer;
private UdpClient udpClient; //Listens and sends data on port 1550, used in
synchronous mode.
private Device device;
private SecondaryBuffer playbackBuffer;
private BufferDescription playbackBufferDescription;
private Socket clientSocket;
private bool bStop; //Flag to end the Start and Receive threads.
private IPEndPoint otherPartyIP; //IP of party we want to make a call.
private EndPoint otherPartyEP;
private volatile bool bIsCallActive; //Tells whether we have an active
call.
private Vocoder vocoder;
private byte[] byteData = new byte[1024]; //Buffer to store the data received.
private volatile int nUdpClientFlag; //Flag used to close the udpClient
socket.

public VoiceChat()
{
InitializeComponent();
Initialize();
}

/*
* Initializes all the data members.
*/
private void Initialize()
{
try
{
device = new Device();
device.SetCooperativeLevel(this, CooperativeLevel.Normal);

CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

DeviceInformation deviceInfo = captureDeviceCollection[0];

capture = new Capture(deviceInfo.DriverGuid);

short channels = 1; //Stereo.


short bitsPerSample = 16; //16Bit, alternatively use 8Bits.
int samplesPerSecond = 22050; //11KHz use 11025 , 22KHz use 22050, 44KHz use 44100
etc.

//Set up the wave format to be captured.


waveFormat = new WaveFormat();
waveFormat.Channels = channels;
waveFormat.FormatTag = WaveFormatTag.Pcm;
waveFormat.SamplesPerSecond = samplesPerSecond;
waveFormat.BitsPerSample = bitsPerSample;
waveFormat.BlockAlign = (short)(channels * (bitsPerSample / (short)8));
waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

captureBufferDescription = new CaptureBufferDescription();


captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond /
5;//approx 200 milliseconds of PCM data.
captureBufferDescription.Format = waveFormat;

playbackBufferDescription = new BufferDescription();


playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
playbackBufferDescription.Format = waveFormat;
playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

24 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

bufferSize = captureBufferDescription.BufferBytes;

bIsCallActive = false;
nUdpClientFlag = 0;

//Using UDP sockets


clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
//Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
clientSocket.Bind(ourEP);

//Receive data from any IP.


EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

byteData = new byte[1024];


//Receive data asynchornously.
clientSocket.BeginReceiveFrom(byteData,
0, byteData.Length,
SocketFlags.None,
ref remoteEP,
new AsyncCallback(OnReceive),
null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-Initialize ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

private void btnCall_Click(object sender, EventArgs e)


{
Call();
}

private void Call()


{
try
{
//Get the IP we want to call.
otherPartyIP = new IPEndPoint(IPAddress.Parse(txtCallToIP.Text), 1450);
otherPartyEP = (EndPoint)otherPartyIP;

//Get the vocoder to be used.


if (cmbCodecs.SelectedText == "A-Law")
{
vocoder = Vocoder.ALaw;
}
else if (cmbCodecs.SelectedText == "u-Law")
{
vocoder = Vocoder.uLaw;
}
else if (cmbCodecs.SelectedText == "None")
{
vocoder = Vocoder.None;
}

//Send an invite message.


SendMessage(Command.Invite, otherPartyEP);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-Call ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}

25 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

private void OnSend(IAsyncResult ar)


{
try
{
clientSocket.EndSendTo (ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-OnSend ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

/*
* Commands are received asynchronously. OnReceive is the handler for them.
*/
private void OnReceive(IAsyncResult ar)
{
try
{
EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);

//Get the IP from where we got a message.


clientSocket.EndReceiveFrom(ar, ref receivedFromEP);

//Convert the bytes received into an object of type Data.


Data msgReceived = new Data(byteData);

//Act according to the received message.


switch (msgReceived.cmdCommand)
{
//We have an incoming call.
case Command.Invite:
{
if (bIsCallActive == false)
{
//We have no active call.

//Ask the user to accept the call or not.


if (MessageBox.Show("Call coming from " + msgReceived.strName +
".\r\n\r\nAccept it?",
"VoiceChat", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
SendMessage(Command.OK, receivedFromEP);
vocoder = msgReceived.vocoder;
otherPartyEP = receivedFromEP;
otherPartyIP = (IPEndPoint)receivedFromEP;
InitializeCall();
}
else
{
//The call is declined. Send a busy response.
SendMessage(Command.Busy, receivedFromEP);
}
}
else
{
//We already have an existing call. Send a busy response.
SendMessage(Command.Busy, receivedFromEP);
}
break;
}

//OK is received in response to an Invite.


case Command.OK:

26 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

{
//Start a call.
InitializeCall();
break;
}

//Remote party is busy.


case Command.Busy:
{
MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
break;
}

case Command.Bye:
{
//Check if the Bye command has indeed come from the user/IP with which
we have
//a call established. This is used to prevent other users from sending
a Bye, which
//would otherwise end the call.
if (receivedFromEP.Equals (otherPartyEP) == true)
{
//End the call.
UninitializeCall();
}
break;
}
}

byteData = new byte[1024];


//Get ready to receive more commands.
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref
receivedFromEP, new AsyncCallback(OnReceive), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

/*
* Send synchronously sends data captured from microphone across the network on port 1550.
*/
private void Send()
{
try
{
//The following lines get audio from microphone and then send them
//across network.

captureBuffer = new CaptureBuffer(captureBufferDescription, capture);

CreateNotifyPositions();

int halfBuffer = bufferSize / 2;

captureBuffer.Start(true);

bool readFirstBufferPart = true;


int offset = 0;

MemoryStream memStream = new MemoryStream(halfBuffer);


bStop = false;
while (!bStop)
{
autoResetEvent.WaitOne();
memStream.Seek(0, SeekOrigin.Begin);
27 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None);


readFirstBufferPart = !readFirstBufferPart;
offset = readFirstBufferPart ? 0 : halfBuffer;

//TODO: Fix this ugly way of initializing differently.

//Choose the vocoder. And then send the data to other party at port 1550.

if (vocoder == Vocoder.ALaw)
{
byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer());
udpClient.Send(dataToWrite, dataToWrite.Length,
otherPartyIP.Address.ToString (), 1550);
}
else if (vocoder == Vocoder.uLaw)
{
byte[] dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer());
udpClient.Send(dataToWrite, dataToWrite.Length,
otherPartyIP.Address.ToString(), 1550);
}
else
{
byte[] dataToWrite = memStream.GetBuffer();
udpClient.Send(dataToWrite, dataToWrite.Length,
otherPartyIP.Address.ToString(), 1550);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-Send ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
captureBuffer.Stop();

//Increment flag by one.


nUdpClientFlag += 1;

//When flag is two then it means we have got out of loops in Send and Receive.
while (nUdpClientFlag != 2)
{ }

//Clear the flag.


nUdpClientFlag = 0;

//Close the socket.


udpClient.Close();
}
}

/*
* Receive audio data coming on port 1550 and feed it to the speakers to be played.
*/
private void Receive()
{
try
{
bStop = false;
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

while (!bStop)
{
//Receive data.
byte[] byteData = udpClient.Receive(ref remoteEP);

//G711 compresses the data by 50%, so we allocate a buffer of double

28 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

//the size to store the decompressed data.


byte[] byteDecodedData = new byte[byteData.Length * 2];

//Decompress data using the proper vocoder.


if (vocoder == Vocoder.ALaw)
{
ALawDecoder.ALawDecode(byteData, out byteDecodedData);
}
else if (vocoder == Vocoder.uLaw)
{
MuLawDecoder.MuLawDecode(byteData, out byteDecodedData);
}
else
{
byteDecodedData = new byte[byteData.Length];
byteDecodedData = byteData;
}

//Play the data received to the user.


playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);
playbackBuffer.Write(0, byteDecodedData, LockFlag.None);
playbackBuffer.Play(0, BufferPlayFlags.Default);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-Receive ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
nUdpClientFlag += 1;
}
}

private void CreateNotifyPositions()


{
try
{
autoResetEvent = new AutoResetEvent(false);
notify = new Notify(captureBuffer);
BufferPositionNotify bufferPositionNotify1 = new BufferPositionNotify();
bufferPositionNotify1.Offset = bufferSize / 2 - 1;
bufferPositionNotify1.EventNotifyHandle =
autoResetEvent.SafeWaitHandle.DangerousGetHandle();
BufferPositionNotify bufferPositionNotify2 = new BufferPositionNotify();
bufferPositionNotify2.Offset = bufferSize - 1;
bufferPositionNotify2.EventNotifyHandle =
autoResetEvent.SafeWaitHandle.DangerousGetHandle();

notify.SetNotificationPositions(new BufferPositionNotify[]
{ bufferPositionNotify1, bufferPositionNotify2 });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-CreateNotifyPositions ()",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btnEndCall_Click(object sender, EventArgs e)


{
DropCall();
}

private void UninitializeCall()


{

29 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

//Set the flag to end the Send and Receive threads.


bStop = true;

bIsCallActive = false;
btnCall.Enabled = true;
btnEndCall.Enabled = false;
}

private void DropCall()


{
try
{
//Send a Bye message to the user to end the call.
SendMessage(Command.Bye, otherPartyEP);
UninitializeCall();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-DropCall ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

private void InitializeCall()


{
try
{
//Start listening on port 1500.
udpClient = new UdpClient(1550);

Thread senderThread = new Thread(new ThreadStart(Send));


Thread receiverThread = new Thread(new ThreadStart(Receive));
bIsCallActive = true;

//Start the receiver and sender thread.


receiverThread.Start();
senderThread.Start();
btnCall.Enabled = false;
btnEndCall.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-InitializeCall ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

/*
* Send a message to the remote party.
*/
private void SendMessage(Command cmd, EndPoint sendToEP)
{
try
{
//Create the message to send.
Data msgToSend = new Data();

msgToSend.strName = txtName.Text; //Name of the user.


msgToSend.cmdCommand = cmd; //Message to send.
msgToSend.vocoder = vocoder; //Vocoder to be used.

byte[] message = msgToSend.ToByte();

//Send the message asynchronously.


clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP,
new AsyncCallback(OnSend), null);
}
catch (Exception ex)

30 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

{
MessageBox.Show(ex.Message, "VoiceChat-SendMessage ()", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

private void VoiceChat_FormClosing(object sender, FormClosingEventArgs e)


{

if (bIsCallActive)
{
UninitializeCall();
DropCall();
}
}

private void VoiceChat_Load(object sender, EventArgs e)


{

}
}

//The commands for interaction between the two parties.


enum Command
{
Invite, //Make a call.
Bye, //End a call.
Busy, //User busy.
OK, //Response to an invite message. OK is send to indicate that call is accepted.
Null, //No command.
}

//Vocoder
enum Vocoder
{
ALaw, //A-Law vocoder.
uLaw, //u-Law vocoder.
None, //Don't use any vocoder.
}

//The data structure by which the server and the client interact with
//each other.
class Data
{
//Default constructor.
public Data()
{
this.cmdCommand = Command.Null;
this.strName = null;
vocoder = Vocoder.ALaw;
}

//Converts the bytes into an object of type Data.


public Data(byte[] data)
{
//The first four bytes are for the Command.
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);

//The next four store the length of the name.


int nameLen = BitConverter.ToInt32(data, 4);

//This check makes sure that strName has been passed in the array of bytes.
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 8, nameLen);
else
this.strName = null;
}

//Converts the Data structure into an array of bytes.


31 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

public byte[] ToByte()


{
List<byte> result = new List<byte>();

//First four are for the Command.


result.AddRange(BitConverter.GetBytes((int)cmdCommand));

//Add the length of the name.


if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));

//Add the name.


if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));

return result.ToArray();
}

public string strName; //Name by which the client logs into the room.
public Command cmdCommand; //Command type (login, logout, send message, etc).
public Vocoder vocoder;
}
}

Uji Coba Aplikasi Voice Chat


Program saat dijalankan

Gambar di PC lain

32 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

V. Kesimpulan
Dari praktikum tentqng text dan voice chat yang telah dilakukan dapat disimpulkan bahwa
- Program voice chat digunakan dengan menggunakan konsep UDP dimana untuk dapat
terkoneksi antara PC satu dengan PC lain, setiap PC harus terhubung didalam suatu
jaringan. PC bisa menggunakan media kabel UTP, Adhoc, wifi ataupun media yang lain
yang dapat menginjinkan PC untu saling berbagi nomor IP,
- Untuk dapat menggunakan voice chat hal yang perlu dilakukan pertama adalah
memastikan apabila komputer terinstal minimal komponen directx 9 dan net framework
2.0, hal ini diperlukan agar library – library yang digunakan untuk melakukan voice chat
bisa digunakan dengan baik,
- Bahasa aras tinggi C# digunakan karena memiliki library yang lebih banyak
dibandingkan dengan bahasa aras ringgi vb, khususnya didalam koneksi jaringan,

33 | M i k r o p r o c e s s o r d a n A n t a r m u k a
Kelompok 1 Job 7- Text and voice chat

- Library – library yang digunakan untuk dapat berkomunikasi melalui jaringan adalah

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound; //menggunakan directx untuk dapat
melakukan komunikasi suara
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using g711audio;

34 | M i k r o p r o c e s s o r d a n A n t a r m u k a

Anda mungkin juga menyukai