-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCP_SOCKET_server.py
More file actions
48 lines (37 loc) · 1.55 KB
/
TCP_SOCKET_server.py
File metadata and controls
48 lines (37 loc) · 1.55 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
import socket
#KILDE https://www.datacamp.com/tutorial/a-complete-guide-to-socket-programming-in-python
def run_server():
# create a socket object
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP
port = 8001
hostname = socket.gethostname()
server_ip = socket.gethostbyname(hostname)
# bind the socket to a specific address and port
server.bind((server_ip, port))
# listen for incoming connections
server.listen(0)
print(f"Listening on {server_ip}:{port}")
# accept incoming connections
client_socket, client_address = server.accept()
print(f"Accepted connection from {client_address[0]}:{client_address[1]}")
# receive data from the client
while True:
request = client_socket.recv(1024)
request = request.decode("utf-8") # convert bytes to string
# if we receive "close" from the client, then we break
# out of the loop and close the conneciton
if request.lower() == "close":
# send response to the client which acknowledges that the
# connection should be closed and break out of the loop
client_socket.send("closed".encode("utf-8"))
break
print(f"Received: {request}")
response = "accepted".encode("utf-8") # convert string to bytes
# convert and send accept response to the client
client_socket.send(response)
# close connection socket with the client
client_socket.close()
print("Connection to client closed")
# close server socket
server.close()
run_server()