def echo_server(address):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(address)
    socket.listen(1)
    while True:
        client, addr = sock.accept()
        echo_client(client, addr)
Beispiel #2
0
    def run(self) -> None:
        """ Runs the tracker server indefinitely.
        """
        while constants.FOREVER:
            try:
                c, addr = self.sock.accept()

            except timeout:
                # Empty Queue
                self.queuey.process_tasks(self.chunky)
                continue

            _logger.warning(f"Received new connection from peer.")
            # Create new TCP connection, send port to peer node.
            socket, port = utils.bind_TCP_port(self.addr)
            socket.listen(constants.MAX_QUEUED_CONNECTIONS)
            c.send(str(port).encode())
            c.close()

            # Add queue
            id, message_queue = self.queuey.add_thread()
            _logger.warning(f"Tracker new connection at port: {port}.")
            # Start thread to communicate with single peer
            t = threading.Thread(target=self.handle_single_peer,
                                 args=(
                                     socket,
                                     id,
                                     message_queue,
                                 ))
            t.start()
Beispiel #3
0
def waitConnect(socket, port=int(sys.argv[1])):
    socket.bind(('', port))
    socket.listen(1)

    con, client = socket.accept()
    print(client, " connected.")

    connected = True
def convProgress(socket):
	socket.listen(0)
	conn, addr = socket.accept()
	while 1:
		data = conn.recv(4096)
		if not data: break
		print data,
	sys.stderr.write("Progress thread exiting!!")
	socket.close()
Beispiel #5
0
def echo_server(adress):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(adress)
    socket.listen(1)
    while True:
        client, addr = socket.accept()
        echo_client(client, addr)


# 需要重点强调的一点是,上面的例子仅仅是为了演示内置的open()函数的一个特性,并且也只适用于基于Unix的系统。
# 如果你想将一个类文件接口作用在一个套接字并希望你的代码可以跨平台,请使用套接字对象的makefile()方法。
# 但是如果不考虑可移植性的话,那上面的解决方案会比使用makefile()性能更好一点。
def start():
    socket.listen()
    print("Waiting for connections")
    while True:
        try:
            conn , addr = socket.accept()
            conn_list.append(conn)
            addr_list.append(addr)
            #threding rerun function with given args 
            Thread = threading.Thread(target=client_handler, args=(conn , addr))
            Thread.start()
        except Exception as e:
            print(e)
            break
def new_unix_socket(socket_path, socket_backlog=None):
    from os.path import exists
    from os import remove
    from socket import socket, AF_UNIX
    
    if socket_backlog is None:
        socket_backlog = 5
    
    socket = socket(AF_UNIX)
    if exists(socket_path):
        remove(socket_path)
    socket.bind(socket_path)
    socket.listen(socket_backlog)
    
    return socket
Beispiel #8
0
    def handle_connections(self):
        socket = self.__get_socket()
        socket.bind(self.__get_addr())
        socket.listen(2)
        print("Waiting for sender...")
        client, client_addr_sender = socket.accept()
        self.__set_client_addr_sender(client_addr_sender)
        print("%s:%s has connected as sender." % client_addr_sender)

        while True:

            msg = client.recv(self.__get_buf_size()).decode("utf8")
            self.put_message_on_queue(msg)
            if msg == "":
                # socket.close()
                break

        print("Waiting for receiver...")
        socket.listen(20)
        receiver, client_addr_receiver = socket.accept()
        self.__set_client_addr_receiver(client_addr_receiver)
        print("%s:%s has connected as receiver." % client_addr_receiver)

        self.send_data(receiver)
Beispiel #9
0
from socket import AF_INET, SOCK_STREAM, socket

socket = socket(AF_INET, SOCK_STREAM)
socket.bind(('localhost', 10000))
socket.listen(1)

def client_thread(conn, addr):
    print("hello " + str(addr[1]))
    while True:
        message = conn.recv(16).decode()
        if(message):
            print(str(addr[1]) + ": " + message)
        else:
            break

while True:
    conn, addr = socket.accept()
    client_thread(conn, addr)
    conn.close()
    socket.close()
    #exit(0)
Beispiel #10
0
BUFSIZ = 1024
BLOCKSIZE = 16

# mapping socket and address
clients = {}
# mapping socket and chat name
names = {}
hosts_keys = {}
cert = RSA()

socket = socket(AF_INET, SOCK_STREAM)

if __name__ == "__main__":

    socket.bind((ADDR, PORT))
    socket.listen(5)

    try:
        print("Waiting for connection...")
        accept_thread = Thread(target=accept_connections, args=(socket, ))
        accept_thread.start()
        accept_thread.join()
    except:
        # you should catch specific errors but this is
        # only needed to close the socket no matter what,
        # since otherwise you won't be able to open another one
        # once you restart the program
        socket.close()

    socket.close()
Beispiel #11
0
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import pickle
from time import sleep

socket = socket(AF_INET, SOCK_STREAM)
socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
socket.bind(("", 2001))
socket.listen(2)
print("Server running...")

player1, player1_addr = socket.accept() # accept player1
print(f"{player1_addr[0]} has been connected")
player2, player2_addr = socket.accept() # accept player2
print(f"{player2_addr[0]} has been connected")

player1_win = False
player2_win = False

player1_shot = 0
player2_shot = 0

player1_coordinates = pickle.loads(player1.recv(1024)) # recv player1 ship coordinates
player2_coordinates = pickle.loads(player2.recv(1024)) # recv player2 ship coordinates


while True:
    # send ready to player1
    if player2_win:
        player1.send(pickle.dumps(["You lose", player1_shot, player2_shot]))
        player2.send(pickle.dumps(["You win", player1_shot, player2_shot]))
    else:
Beispiel #12
0
    def bind_socket(self, socket: socket) -> None:
        socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        socket.bind(('0.0.0.0', 14143))
        socket.listen(10)  # 10 clients max

        print(colored(f'Serving at http://localhost:14143', 'green'))
Beispiel #13
0
from socket import socket, AF_INET, SOCK_STREAM
import time
import serial
from django.conf import settings
from utils import sendMsg, recvMsg, abnormalShutdown
def server_port():
    return 12322

if __name__ == "__main__":
    # Create socket object
    socket = socket(AF_INET, SOCK_STREAM)
    # Bind socket to localhost on defined port
    socket.bind(('', server_port()))
    # Start listening
    socket.listen(0)
    
    while True:
        # Accept connections while server is alive
        conn, address = socket.accept()
        
        # Print connection information
        #print("Connection received from client address " + str(address[0]) + " on port " + str(address[1]))
        
        # Try to receive incoming message and starting time
        incomingMsg = recvMsg(conn)
        # Print message from client
        #print("Received from client: " + str(incomingMsg))

        ser = serial.Serial(settings.TTY_PORT, '9600', timeout=5)
        time.sleep(2)
# socket allows connections to come into the server on a given port
# the server variable will be an ip address
server = "10.0.18.251"
port = 5555
max_clients_at_once = 2

# ipv4, type of socket, sockstream is how the server string comes in?
socket = socket(AF_INET, SOCK_STREAM)

try:
    socket.bind((server, port))
except error as e:
    print(str(e))

print("Waiting for connection, server started")
socket.listen(max_clients_at_once)

players = [
    Player((0, 0), 50, 50, (255, 0, 0)),
    Player((100, 100), 50, 50, (180, 140, 15))
]


def client_thread(connection, _current_player):
    player_index = 0 if _current_player > 0 else 1
    connection.send(pickle.dumps(players[player_index]))
    msg = ""
    connectedToClient = True
    while connectedToClient:
        print()
        # IF YOU GET ANY ERRORS LIKE 'thing was truanced in size'
Beispiel #15
0
from queue import Queue, Empty
from select import select
from socket import AF_INET, SOCK_STREAM, socket, error

buf_size = 1024

socket = socket(AF_INET, SOCK_STREAM)
socket.setblocking(False)
socket.bind(("localhost", 125))
socket.listen(10)
inputs = [socket]
outputs = []

message_queues = {}

while inputs:
    readable, writable, exceptional = select(inputs, outputs, inputs)
    for s in readable:
        if s is socket:
            conn, addr = s.accept()
            print("Conected:", conn)
            conn.setblocking(False)
            conn.sendall(b"Hello")
            inputs.append(conn)
            message_queues[conn] = Queue()
        else:
            try:
                data = s.recv(buf_size)
            except error:
                if s in outputs:
                    outputs.remove(s)