Professional Documents
Culture Documents
Agus Widaksono - P2K
Agus Widaksono - P2K
JARINGAN KOMPUTER
NIM : 22104410069
NAMA : AGUS WIDAKSONO
JURUSAN : TEKNIK INFORMATIKA
KELAS : TI C 2022
except Exception as e:
print(f'Error to handle user connection: {e}')
remove_connection(connection)
break
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
while True:
try:
msg = connection.recv(1024)
except Exception as e:
print(f'Error handling message from server: {e}')
connection.close()
break
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!')
if msg == 'quit':
break
except Exception as e:
print(f'Error connecting to server socket {e}')
socket_instance.close()
if __name__ == "__main__":
client()
FUngsi handle_user_connection
Fungsi ini menghapus koneksi dari daftar dan menutup soket koneksi.
if __name__ == "__main__":
server()
if __name__ == "__main__":
client()