def writelog(): socket.bind(('', int(receiver_port))) global log log = open('Receiver_log.txt', "w") Receiver = receiver(receiver_port, filename) beginTime, startwaiting, addnum = Receiver.handshake() print("handshake done!") Data = ReceiveData(receiver_port, filename, beginTime, startwaiting) L = Data.Transport() L[1] += addnum log.write( '===============================================================================\n' ) log.write('{:50s}{:5d}\n'.format('Amount of Data Received (bytes)', L[0])) log.write('{:50s}{:5d}\n'.format('Total segments received', L[1])) log.write('{:50s}{:5d}\n'.format('Data segments received', L[2])) log.write('{:50s}{:5d}\n'.format('Data Segments with bit errors', L[3])) log.write('{:50s}{:5d}\n'.format('Duplicate data segments received', L[4])) log.write('{:50s}{:5d}\n'.format('Duplicate Acks sent', L[5])) log.write( '===============================================================================\n' ) log.close()
def time_server(address): sock = socket(AF_INET, SOCK_DGRAM) socket.bind(address) while True: msg, addr = sock.recvfrom(8192) print('Got message from ', addr) resp = time.ctime() sock.sendto(resp.encode('ascii'), addr)
def waitConnect(socket, port=int(sys.argv[1])): socket.bind(('', port)) socket.listen(1) con, client = socket.accept() print(client, " connected.") connected = True
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
def __init__(self, ifname, bpf=None): self.ifname = ifname # lookup the interface details with IPRoute() as ip: for link in ip.get_links(): if link.get_attr("IFLA_IFNAME") == ifname: break else: raise IOError(2, "Link not found") self.l2addr = link.get_attr("IFLA_ADDRESS") self.ifindex = link["index"] # bring up the socket socket.__init__(self, AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) socket.bind(self, (self.ifname, ETH_P_ALL)) if bpf: fstring, self.fprog = compile_bpf(bpf) socket.setsockopt(self, SOL_SOCKET, SO_ATTACH_FILTER, fstring)
def __init__(self, ifname, bpf=None): self.ifname = ifname # lookup the interface details with IPRoute() as ip: for link in ip.get_links(): if link.get_attr('IFLA_IFNAME') == ifname: break else: raise IOError(2, 'Link not found') self.l2addr = link.get_attr('IFLA_ADDRESS') self.ifindex = link['index'] # bring up the socket socket.__init__(self, AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) socket.bind(self, (self.ifname, ETH_P_ALL)) if bpf: fstring, self.fprog = compile_bpf(bpf) socket.setsockopt(self, SOL_SOCKET, SO_ATTACH_FILTER, fstring)
def receiver(self, socket): config = component.get("Config") # bind udp listener interface = config.get('adapters.ethernet.interface', '0.0.0.0') port = config.get('adapters.ethernet.port', '4444') socket.bind((interface, port)) logger.debug('Binded on port: ' + str(port)) counter = 0 while True: # blocking read datagram, address = socket.recvfrom(1024) # put datagram to queue self.rq.put([datagram, address])
def __init__(self, ifname, bpf=None): self.ifname = ifname # lookup the interface details with IPRoute() as ip: for link in ip.get_links(): if link.get_attr('IFLA_IFNAME') == ifname: break else: raise IOError(2, 'Link not found') self.l2addr = link.get_attr('IFLA_ADDRESS') self.ifindex = link['index'] # bring up the socket socket.__init__(self, AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) socket.bind(self, (self.ifname, ETH_P_ALL)) if bpf: self.clear_buffer() fstring, self.fprog = compile_bpf(bpf) socket.setsockopt(self, SOL_SOCKET, SO_ATTACH_FILTER, fstring) else: self.clear_buffer(remove_total_filter=True)
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)
from socket import socket, SOCK_DGRAM, AF_INET from pickled_calculator import process import pickle import threading def handle(data, remote): expression = pickle.loads(data) try: result = process(expression) print('Resolved', expression, 'to', result) socket.sendto(pickle.dumps(result), remote) except Exception as error: socket.sendto(pickle.dumps({'error': str(error)}), remote) ADDRESS = ('', 8080) with socket(AF_INET, SOCK_DGRAM) as socket: socket.bind(ADDRESS) while True: data, remote = socket.recvfrom(1024) threading.Thread(None, handle, args=(data, remote)).start()
PORT = 33000 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()
from socket import socket, AF_INET, SOCK_DGRAM socket = socket(family=AF_INET, type=SOCK_DGRAM) socket.bind(("localhost", 8003)) while True: info = input("输入信息:") socket.sendto(info.encode("utf-8"), ("localhost", 8002))
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'))
conn = tuple(conn) nm = None # Obtener desición. server = confirm('¿Desea ser un servidor?', ' ([y] Sí | [n] No): ') logger.debug('La elección del usuario al ser servidor es: %s', server) # Crear el socket. logger.info('Creando zócalo de red') socket = socket() if server: # Crear la escucha. logger.debug('Escuchando la dirección "%s:%d"', *conn) try: socket.bind(conn) except OSError: logger.critical( 'La dirección no está disponible para ser usada como servidor') pause() sys.exit(1) except GAIError: logger.critical('No es una dirección válida.') pause() sys.exit(1) # Escuchar solamente una conexión. logger.info('Aceptando solamente una conexión') socket.listen(1) # Acceptar la conexión. c, ip = socket.accept() logger.debug('Conexión aceptada por: "%s:%d"', *ip)
from socket import socket with socket() as socket: socket.bind(('', 4000)) socket.listen(1) while True: conn, addr = socket.accept() recv_msg = conn.recv(1024) print(recv_msg.decode()) send_msg = 'OK' conn.sendall(send_msg.encode()) conn.close()
#!/usr/bin/env python 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)
from _thread import * import sys import os import time # 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]))
from socket import socket, AF_INET, SOCK_DGRAM import sys HOST = "0.0.0.0" PORT_NUMBER = 8080 SIZE = 1024 socket = socket(AF_INET, SOCK_DGRAM) socket.bind((HOST, PORT_NUMBER)) print("Server listening on port {0}\n".format(PORT_NUMBER)) i = 0 while True: (data, addr) = socket.recvfrom(SIZE) if data == b'stop': break with open("recieved_udp", 'ab+') as f: f.write(data) print(f"==================={i}===================") print(data) i += 1 socket.close() sys.exit()
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)
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:
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM, gethostname, SOCK_DGRAM import pickle import sys #THIS FILE SHOULD BE RUN WHEN MULTIPLAYER IS DESIRED. ONLY ONE PLAYER NEEDS TO RUN THIS FILE TO HOST MULTIPLAYER #Written based off of Documentation of Sockets Example 18.1.15 https://docs.python.org/3/library/socket.html#timeouts-and-the-accept-method clients = {'player1': None, 'player2': None} PORT_NUMBER = 5009 SIZE = 4096 hostName = gethostbyname(gethostname()) socket = socket(AF_INET, SOCK_DGRAM) socket.bind((hostName, PORT_NUMBER)) print("Test server listening on port %s\n at %s\n\n" % (str(PORT_NUMBER), str(gethostbyname(gethostname())))) while True: incoming = socket.recvfrom(SIZE) (data, addr) = incoming if pickle.loads(data) == '': if clients.get('player2', None) == None: if clients.get('player1', None) != None: clients['player2'] = addr print('Player 2 Connected') else: clients['player1'] = addr print('Player 1 Connected') if incoming[1] == clients['player1']:
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)