Udp Client
Udp Client
socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
True:
{}'.format(client_address, data.decode()))
server_socket.sendto(response.encode(), client_address)
while True:
data, client_address = server_socket.recvfrom(1024)
print('Received data from {}: {}'.format(client_address, data.decode()))
response = 'Hello, client!'
server_socket.sendto(response.encode(), client_address)
SERVER SIDE TCP: import
socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 12345) try:
server_socket.bind(server_address)
server_socket.listen(1)
print('TCP server is listening on {}:{}'.format(*server_address))
print('Waiting for a connection...')
client_socket, client_address = server_socket.accept()
print('Connected to', client_address) data =
client_socket.recv(1024)
print('Received data from client:', data.decode())
except Exception as e:
print('Error:', e) finally:
# Close the client socket and the server socket in the finally block
if 'client_socket' in locals():
client_socket.close()
server_socket.close() Clint side TCP: import
socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 12345) try:
client_socket.connect(server_address)
print('Connected to', server_address)
message = 'Hello, server!'
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print('Received response from server:', data.decode())
except Exception as e: print('Error:', e) finally:
# Close the socket in the finally block
client_socket.close()