06/01/2014, 07:17
|
| | Fecha de Ingreso: noviembre-2013
Mensajes: 61
Antigüedad: 11 años, 1 mes Puntos: 0 | |
Respuesta: Chat sencillo TCP Cita:
Iniciado por razpeitia Usando solo select y sockets.
Código Python:
Ver originalimport select import socket import sys import re CONNECTION_LIMIT = 10 HOST, PORT = 'localhost', 8080 # Create a TCP/IP socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(0) # Bind the socket to the port server_address = (HOST, PORT) print >>sys.stderr, 'starting up on %s port %s' % server_address server.bind(server_address) # Listen for incoming connections server.listen(10) # Sockets from which we expect to read inputs = [ server ] # Sockets to which we expect to write outputs = [ ] # User list users = {} def broadcast(sockets, message): for s in sockets: s.send(message) while True: readable, writable, exceptional = select.select(inputs, outputs, inputs) # Handle inputs for s in readable: if s is server: # A "readable" server socket is ready to accept a connection connection, client_address = s.accept() connection.setblocking(0) inputs.append(connection) outputs.append(connection) users[connection] = "nameless" username = users[connection] broadcast(outputs, '%s has enter' % username) else: data = s.recv(1024) if data: # A readable client socket has data data = data.strip() m = re.match(r'^/nick (\w+)$', data, re.I) if m: old_username = users[s] users[s] = m.group(1) data = '%s is now %s' % (old_username, users[s]) else: data = "%s > %s" % (users[s], data) broadcast(outputs, data) else: # Stop listening for input on the connection username = users[s] outputs.remove(s) inputs.remove(s) s.close() broadcast(outputs, '%s has left' % username) # Handle "exceptional conditions" for s in exceptional: # Stop listening for input on the connection inputs.remove(s) outputs.remove(s) s.close()
Código Python:
Ver original# client.py import socket import sys import select import Queue HOST, PORT = 'localhost', 8080 server_address = (HOST, PORT) # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) inputs = [sys.stdin, sock] outputs = [sock] queue = Queue.Queue() while True: readable, writable, exceptional = select.select(inputs, outputs, inputs) for r in readable: if r is sys.stdin: message = sys.stdin.readline() queue.put(message) elif r is sock: data = sock.recv(1024) if not data: sock.close() print "Connection closed" sys.exit(0) else: print data for w in writable: if w is sock: try: next_msg = queue.get_nowait() sock.send(next_msg) except Queue.Empty: pass for ex in exceptional: if ex is sock: sock.close()
PD: Esto no funcionara en windows. El servidor si, pero el cliente no.
Por que no funcionaria el cliente?
Un saludo |