Created
July 9, 2020 05:48
-
-
Save Anjaan-g/3682eced98ff67988e0cb3e81ebffc90 to your computer and use it in GitHub Desktop.
Socket Programming to connect server and client on same network(eg. wifi, LAN).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
HEADER = 64 | |
PORT = 5050 | |
FORMAT = 'utf-8' | |
DISCONNECT_MSG = "!DISCONNECT" | |
SERVER = socket.gethostbyname(socket.gethostname()) | |
ADDR = (SERVER, PORT) | |
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
client.connect(ADDR) | |
def send(msg): | |
message = msg.encode(FORMAT) | |
msg_length = len(message) | |
send_length = str(msg_length).encode(FORMAT) | |
send_length += b' ' * (HEADER - len(send_length)) | |
client.send(send_length) | |
client.send(message) | |
print(client.recv(2048).decode(FORMAT)) | |
send("Hello Anjaan!") | |
input() | |
send("Type any message to send") | |
input() | |
send(DISCONNECT_MSG) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import threading | |
HEADER = 64 | |
PORT = 5050 | |
# SERVER = "192.168.100.34" '''This is hardcoded for this computer''' | |
SERVER = socket.gethostbyname(socket.gethostname()) #This is dynamic and works on every computer. | |
ADDR = (SERVER,PORT) | |
FORMAT = 'utf-8' | |
DISCONNECT_MSG = "!DISCONNECT" | |
#Type of addresses we're working with. | |
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) | |
server.bind(ADDR) | |
def handle_client(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_MSG: | |
connected = False | |
print(f"[{addr}]{msg}") | |
conn.send("Msg Received".encode(FORMAT)) | |
conn.close() | |
def start(): | |
server.listen() | |
print(f"[LISTENING] Server is listening at {SERVER}") | |
while True: | |
conn, addr = server.accept() | |
thread = threading.Thread(target=handle_client, args=(conn, addr)) | |
thread.start() | |
print(f"[ACTIVE CONNECTIONS] {threading.activeCount()-1}") | |
print("[STARTING] server is starting...") | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment