You are on page 1of 9

LAPORAN

JARINGAN KOMPUTER

Dosen Pengampu: Muhamad Faried Rahmat, S.ST., M.Tr.T.

PENJELASAN DAN CARA KERJA PROGRAM CHAT

NIM : 22104410069
NAMA : AGUS WIDAKSONO
JURUSAN : TEKNIK INFORMATIKA
KELAS : TI C 2022

JURUSAN TEKNIK INFORMATIKA


FAKULTAS TEKNOLOGI INFORMASI
UNIVERSITAS ISLAM BALITAR
2023
1.1. Source code
1.1.1. Main.py
import socket, threading

# Global variable that mantain client's connections


connections = []

def handle_user_connection(connection: socket.socket, address: str)


-> None:
'''
Get user connection in order to keep receiving their
messages and
sent to others users/connections.
'''
while True:
try:
# Get client message
msg = connection.recv(1024)

# If no message is received, there is a chance that


connection has ended
# so in this case, we need to close connection and
remove it from connections list.
if msg:
# Log message sent by user
print(f'{address[0]}:{address[1]} -
{msg.decode()}')

# Build message format and broadcast to users


connected on server
msg_to_send = f'From {address[0]}:{address[1]} -
{msg.decode()}'
broadcast(msg_to_send, connection)

# Close connection if no message was sent


else:
remove_connection(connection)
break

except Exception as e:
print(f'Error to handle user connection: {e}')
remove_connection(connection)
break

def broadcast(message: str, connection: socket.socket) -> None:


'''
Broadcast message to all users connected to the server
'''

# Iterate on connections in order to send message to all


client's connected
for client_conn in connections:
# Check if isn't the connection of who's send
if client_conn != connection:
try:
# Sending message to client connection
client_conn.send(message.encode())
# if it fails, there is a chance of socket has died
except Exception as e:
print('Error broadcasting message: {e}')
remove_connection(client_conn)

def remove_connection(conn: socket.socket) -> None:


'''
Remove specified connection from connections list
'''

# Check if connection exists on connections list


if conn in connections:
# Close socket connection and remove connection from
connections list
conn.close()
connections.remove(conn)

def server() -> None:


'''
Main process that receive client's connections and start a
new thread
to handle their messages
'''

LISTENING_PORT = 12000

try:
# Create server and specifying that it can only handle 4
connections by time!
socket_instance = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
socket_instance.bind(('', LISTENING_PORT))
socket_instance.listen(4)

print('Server running!')

while True:
# Accept client connection
socket_connection, address = socket_instance.accept()
# Add client connection to connections list
connections.append(socket_connection)
# Start a new thread to handle client connection and
receive it's messages
# in order to send to others connections
threading.Thread(target=handle_user_connection,
args=[socket_connection, address]).start()

except Exception as e:
print(f'An error has occurred when instancing socket: {e}')
finally:
# In case of any problem we clean all connections and close
the server connection
if len(connections) > 0:
for conn in connections:
remove_connection(conn)

socket_instance.close()
if __name__ == "__main__":
server()

1.1.2. Client.py
import socket, threading

def handle_messages(connection: socket.socket):


'''
Receive messages sent by the server and display them to
user
'''

while True:
try:
msg = connection.recv(1024)

# If there is no message, there is a chance that


connection has closed
# so the connection will be closed and an error will be
displayed.
# If not, it will try to decode message in order to
show to user.
if msg:
print(msg.decode())
else:
connection.close()
break

except Exception as e:
print(f'Error handling message from server: {e}')
connection.close()
break

def client() -> None:


'''
Main process that start client connection to the server
and handle it's input messages
'''

SERVER_ADDRESS = '127.0.0.1'
SERVER_PORT = 12000

try:
# Instantiate socket and start connection with server
socket_instance = socket.socket()
socket_instance.connect((SERVER_ADDRESS, SERVER_PORT))
# Create a thread in order to handle messages sent by
server
threading.Thread(target=handle_messages,
args=[socket_instance]).start()

print('Connected to chat!')

# Read user's input until it quit from chat and close


connection
while True:
msg = input()

if msg == 'quit':
break

# Parse message to utf-8


socket_instance.send(msg.encode())

# Close connection with the server


socket_instance.close()

except Exception as e:
print(f'Error connecting to server socket {e}')
socket_instance.close()

if __name__ == "__main__":
client()

1.2. Penjelasan program


1.2.1. main.py /skript server
import socket, threading

# Global variable that mantain client's connections


connections = []

 Skrip mengimpor modul socket dan threading untuk mengelola


komunikasi jaringan dan threading.
 Variabel connections adalah daftar yang menyimpan soket klien yang
terhubung ke server.

def handle_user_connection(connection: socket.socket,


address: str) -> None:
# ...

FUngsi handle_user_connection

 Fungsi ini menangani pesan dari klien yang terhubung.


 Berjalan dalam loop tak terbatas untuk terus menerima pesan dari klien.
 Memproses pesan yang diterima dan menyebarkannya ke klien lain
menggunakan fungsi broadcast.
 Jika koneksi ditutup, menghapus koneksi dari daftar.

def broadcast(message: str, connection: socket.socket) ->


None:
# ...
 Fungsi ini menyebarkan pesan ke semua klien yang terhubung, kecuali
pengirim pesan.
 Menggunakan loop untuk mengirim pesan ke setiap klien dalam daftar
koneksi.

def remove_connection(conn: socket.socket) -> None:


# ...

 Fungsi ini menghapus koneksi dari daftar dan menutup soket koneksi.

def server() -> None:


# ...

 Fungsi utama untuk menjalankan server.


 Membuat socket server, mengikatnya ke alamat dan port tertentu, dan
mulai mendengarkan koneksi masuk.
 Setiap koneksi baru ditambahkan ke daftar dan ditangani oleh thread
terpisah.

if __name__ == "__main__":
server()

 Menjalankan fungsi server ketika skrip dijalankan.

1.2.2. Client.py / script client


import socket, threading

 Skrip mengimpor modul socket dan threading untuk mengelola


komunikasi jaringan dan threading.

def handle_messages(connection: socket.socket):


# ...

 Fungsi ini menangani pesan yang diterima dari server.


 Berjalan dalam loop tak terbatas untuk terus menerima dan mencetak
pesan dari server.
 Jika koneksi ditutup, keluar dari loop.

def handle_messages(connection: socket.socket):


# ...
 Fungsi ini menangani pesan yang diterima dari server.
 Berjalan dalam loop tak terbatas untuk terus menerima dan mencetak
pesan dari server.
 Jika koneksi ditutup, keluar dari loop.

def client() -> None:


# ...

 Fungsi utama untuk menjalankan klien.


 Membuat socket klien, terhubung ke server, dan memulai thread untuk
menangani pesan dari server.
 Menerima input pengguna dan mengirimnya ke server.
 Jika pengguna memasukkan "quit," keluar dari loop dan menutup
koneksi.

if __name__ == "__main__":
client()

 Menjalankan fungsi klien ketika skrip dijalankan.

1.3. Cara menjalankan program

Buka direktori tempat di mana program diletakkan kemudian klik


kananopen in terminal
Kemudian ketikkan python main.py 127.0.0.1 8383 sampai ada tulisan server
running
Kemudian
Duplicat terminal untuk menjalankan client

Kemudian ketiikan python client.py 127.0.0.1 8383

Hingga ada tulisan connected to chat


Kita coba chat seperti ini pada terminal client

Maka pada sisi terminal server akan muncul chat

You might also like