-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·52 lines (31 loc) · 1.13 KB
/
Copy pathmain.py
File metadata and controls
executable file
·52 lines (31 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# first of all import the socket library
import socket
# set up the host and port
# localhost same as 127.0.0.1
host = "localhost"
# select a port which is free
port = 5050
# Identify the sockets address family like ipv4 in this case
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
""" The code still works without (socket.AF_INET, socket.SOCK_STREAM) but if you are creating a multi client system
then you need it.
"""
# bind the server to the address
server.bind((host, port))
# put server in listening mode
server.listen()
print("socket is listening")
while True:
"""Use try and except method to tackle errors and exceptions"""
try:
client, addr = server.accept()
name = client.recv(1024).decode("utf-8")
print('Got connection from', addr, name)
# send a message to client.
# use encode and decode to convert bytes to strings
client.send('Connected Successfully'.encode("utf-8"))
# Close the connection with the client
client.close()
except Exception as e:
print("[Exception]", e)
#