Created
February 15, 2022 17:51
-
-
Save FreeFly19/86642812090b8bfcc23dc3c15f225c98 to your computer and use it in GitHub Desktop.
Python TCP server and client
This file contains hidden or 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 sys | |
import threading | |
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
socket.connect(('127.0.0.1', 9999)) | |
def read_from_socket(socket): | |
while True: | |
message = socket.recv(2048) | |
if len(message) > 0: | |
print(message.decode('utf-8')) | |
t = threading.Thread(target=read_from_socket, args=(socket,)) | |
t.start() | |
while True: | |
sockets_list = [sys.stdin, socket] | |
message = input() | |
socket.send(bytes(message, 'utf-8')) | |
socket.close() |
This file contains hidden or 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 | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server.bind(('0.0.0.0', 9999)) | |
server.listen(100) | |
list_of_clients = [] | |
def clientthread(conn, addr): | |
conn.send(bytes("Welcome to this chatroom!", 'utf-8')) | |
while True: | |
try: | |
message = conn.recv(2048) | |
if message: | |
message = message.decode('utf-8') | |
print("<" + addr[0] + "> " + message) | |
message_to_send = "<" + addr[0] + "> " + message | |
message_to_send = bytes(message_to_send, 'utf-8') | |
broadcast(message_to_send, conn) | |
else: | |
"""message may have no content if the connection | |
is broken, in this case we remove the connection""" | |
remove(conn) | |
except: | |
continue | |
def broadcast(message, connection): | |
for clients in list_of_clients: | |
if clients != connection: | |
try: | |
clients.send(message) | |
except: | |
clients.close() | |
remove(clients) | |
def remove(connection): | |
if connection in list_of_clients: | |
list_of_clients.remove(connection) | |
while True: | |
conn, addr = server.accept() | |
list_of_clients.append(conn) | |
print(addr[0] + " connected") | |
t = threading.Thread(target=clientthread, args=(conn, addr)) | |
t.start() | |
conn.close() | |
server.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment