Skip to content

Commit 00f705b

Browse files
authored
Simple python socket server
1 parent b48dbcf commit 00f705b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

server.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import socket
2+
import sys
3+
4+
HOST = '' # interface
5+
PORT = 8888 # port
6+
7+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
8+
print('Socket created')
9+
10+
# Bind socket to local host and port
11+
try:
12+
s.bind((HOST, PORT))
13+
except socket.error as msg:
14+
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
15+
sys.exit()
16+
17+
print('Socket bind complete')
18+
19+
# Start listening on socket
20+
s.listen(10)
21+
print('Socket now listening')
22+
23+
# now keep talking with the client
24+
while 1:
25+
conn, addr = s.accept()
26+
print('Connected with ' + addr[0] + ':' + str(addr[1]))
27+
conn.send(b'Welcome to the server. Type something and hit enter\n')
28+
while True:
29+
data = conn.recv(1024)
30+
reply = 'Reply text\n'
31+
if not data:
32+
break
33+
34+
conn.sendall(bytes(reply, 'utf-8'))
35+
36+
conn.close()
37+
38+
s.close()
39+
40+
41+
# To test just use:
42+
# >>> telnet localhost 8888

0 commit comments

Comments
 (0)