Skip to content

Instantly share code, notes, and snippets.

@meain
Created November 19, 2017 16:19
Show Gist options
  • Save meain/a036b74a7151779de31d53ff1955857f to your computer and use it in GitHub Desktop.
Save meain/a036b74a7151779de31d53ff1955857f to your computer and use it in GitHub Desktop.
NOS Lab
import socket, select, sys
host = "localhost"
port = 9009
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
while 1:
read, write, error = select.select([sock, sys.stdin], [], [])
for s in read:
if s == sock:
data = s.recv(1024)
print data
if s == sys.stdin:
data = sys.stdin.readline()
sys.stdout.flush()
sock.send(data)
import socket, select
host = "localhost"
port = 9009
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(10)
sock_list = []
sock_list.append(server_socket)
def broadcast(sock, message):
print "Broadcasting...", message
for s in sock_list:
try:
if s != server_socket and s != sock:
s.send(message)
except:
broadcast(sock, "Removing: " + str(sock))
s.close()
if s in sock_list:
sock_list.remove(s)
while 1:
# inside loop as sock_list can change
read, write, error = select.select(sock_list, [], [])
for sock in read:
if sock == server_socket:
# new conn
cs, addr = server_socket.accept()
sock_list.append(cs)
broadcast(cs, "JOIN: " + str(cs))
else:
try:
data = sock.recv(1024)
print data
if data:
broadcast(sock, str(sock) + " : " + data)
else:
broadcast(sock, "Removing: " + str(sock))
if sock in sock_list:
sock_list.remove(sock)
except:
continue
# it works but don't know if its the right way to do it
import os
# create two pipes
r, w = os.pipe()
r2, w2 = os.pipe()
# fork a process
# the proces with pid will be the parent proces
pid = os.fork()
if pid: # parent
os.close(r)
os.close(w2)
w = os.fdopen(w, 'w')
w.write("snow")
w.close()
r2 = os.fdopen(r2)
print r2.read()
else: # child
os.close(w)
os.close(r2)
r = os.fdopen(r)
data = r.read()
print data
w2 = os.fdopen(w2, 'w')
w2.write("ponies")
w2.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment