First Commit
This commit is contained in:
commit
df8436e0b7
4 files changed
+70
No files matched your search
@@ -0,0 +1,3 @@
|
|||||||
|
# Python Socket
|
||||||
|
|
||||||
|
This is Just what I have learnt in python socket. Nothing Special at all.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import socket
|
||||||
|
|
||||||
|
HEADER = 64
|
||||||
|
PORT = 5050
|
||||||
|
FORMAT = 'utf-8'
|
||||||
|
DISCONNECT_MESSAGE = '!DISCONNECT'
|
||||||
|
SERVER = '169.254.95.158'
|
||||||
|
ADDR = (SERVER, PORT)
|
||||||
|
|
||||||
|
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
try:
|
||||||
|
client.connect(ADDR)
|
||||||
|
def send(msg):
|
||||||
|
message = msg.encode(FORMAT)
|
||||||
|
msg_length = len(msg)
|
||||||
|
send_length = str(msg_length).encode(FORMAT)
|
||||||
|
send_length += b' ' * (HEADER - len(send_length))
|
||||||
|
client.send(send_length)
|
||||||
|
client.send(message)
|
||||||
|
|
||||||
|
print('Type "disconnect" to disconnect from the server.')
|
||||||
|
while True:
|
||||||
|
x = input('>')
|
||||||
|
if x.upper() == 'DISCONNECT':
|
||||||
|
send(DISCONNECT_MESSAGE)
|
||||||
|
break
|
||||||
|
else: send(x)
|
||||||
|
except ConnectionRefusedError: print('Unable to Connect to server.\nThe Server may be down or is unavailable.')
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
|
||||||
|
HEADER = 64
|
||||||
|
PORT = 5050
|
||||||
|
SERVER = socket.gethostbyname(socket.gethostname())
|
||||||
|
ADDR = (SERVER, PORT)
|
||||||
|
FORMAT = 'utf-8'
|
||||||
|
DISCONNECT_MESSAGE = '!DISCONNECT'
|
||||||
|
|
||||||
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
server.bind(ADDR)
|
||||||
|
|
||||||
|
def handleClient(conn, addr):
|
||||||
|
print(f'[NEW CONNECTION] - {addr} connected.')
|
||||||
|
connected = True
|
||||||
|
while connected:
|
||||||
|
msg_length = conn.recv(HEADER).decode(FORMAT)
|
||||||
|
if msg_length:
|
||||||
|
msg_length = int(msg_length)
|
||||||
|
msg = conn.recv(msg_length).decode(FORMAT)
|
||||||
|
if msg == DISCONNECT_MESSAGE: break
|
||||||
|
print(f'[{addr}] - {msg}')
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def start():
|
||||||
|
server.listen()
|
||||||
|
print(f'[LISTENING] - Server is listening on {SERVER}')
|
||||||
|
while True:
|
||||||
|
conn, addr = server.accept()
|
||||||
|
thread = threading.Thread(target=handleClient, args=(conn, addr))
|
||||||
|
thread.start()
|
||||||
|
thread2 = threading.Thread(target=quit)
|
||||||
|
thread2.start()
|
||||||
|
print(f'[ACTIVE CONNECTIONS] - {threading.activeCount() - 1}')
|
||||||
|
|
||||||
|
print('[Starting] - Server Starting...')
|
||||||
|
start()
|
||||||
Reference in new issue
Block a user