Answers for "simple socket server python"

0

make a socket server side python

import socket
import threading

HOST = '127.0.0.1'
PORT = 9090

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

server.listen()

clients = []
nickname = []

def broadcast(message):
    for client in clients:
        client.send(message)

def handle(client, address):
    while True:
        try:
            message = client.recv(1024).decode('utf-8')
            print(f"Client {str(address)} says {message}")
            broadcast(message)
        except:
            clients.remove(client)
            print(f"Client {address} disconnected")
            client.close()
            pass

def receive():
    while True:
        client, address = server.accept()
        print(f"Connected with {str(address)}!")
        clients.append(client)
        broadcast(f"Client {address} connected to the server".encode('utf-8'))
        client.send("Connected to the server".encode('utf-8'))
        thread = threading.Thread(target=handle, args=(client, address))
        thread.start()

print("Server running...")

receive()
Posted by: Guest on August-24-2021
6

socket programming in python

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)
Posted by: Guest on August-26-2020
1

tcp server using sockets in python

import socket
from socket import *
import json

serverPort = 6100
serverSocket = socket(AF_INET, SOCK_STREAM)
# Avoiding : Python [Errno 98] Address already in use


serverSocket.bind(("", serverPort))
serverSocket.listen(1)

# TCP Server
print("The server is listening on PORT 6100")

while 1:

	connectionSocket, addr = serverSocket.accept()
	data = connectionSocket.recv(1024)

	# De-serializing data
	data_loaded = json.loads(data)
	
	print("client Sent :\n ", data_loaded)
	
	# Sending response
	connectionSocket.send(str.encode("Mil gya data"))


connectionSocket.close()
Posted by: Guest on November-15-2020

Python Answers by Framework

Browse Popular Code Answers by Language