I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from threading import Thread
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow :
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam
"""
def sendmail(exp,dest,msg):
server = dest.split("#")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
#contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(Thread):
def __init__self(self):
Thread.__init__(self)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 25)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
class Pages :
def root(self,cgi=None):
return """eNqtVV1zqkgQfedX3MrrbNVREBnu5ubWCCoajPiRaHyTxEGNiAKC8uu3B7Nb+7JvO1QNNAOnT5/u
6Xnc5vHhSXsMk8/bk5bv7tdjmNK7XRz9yNKPXw+f63z9cxevow12H8mf4TrbtFt/CCE6QnRFl2Z1
H4hOoh57EU2OmsRETQPx9/p/D+3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U58ANyLr7J2669QcyFjSTkdnGDI/0
izmIMrqF7PYHtAd8/LhWeBtNTj1l0rlzja6DO1asvESKmpDzYKmkrOPS+39hmT3Td2zbtG26kzMb
FF0bFd+XKi58We6mr3uvqGgAQyVQ1hSGkRCNMdEIi0a/2yDa57HyFYTWKDo2mHzz9Cxif/+h76L7
lzipaVfkbBLLcITnxo9LPhHxMKD/QeQfHOrtILg+k88eTeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6"""
class Serverhttp(Thread):
def __init__(self):
Thread.__init__(self)
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def run(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 41000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
self.sock.bind(server_address)
# Listen for incoming connections
self.sock.listen(1)
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = self.sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
connection, client_address = self.sock.accept()
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
self.sock.close()
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
def traitement(self,data):
url = self.POST.findall(data)
print url
print len(url)
url = self.GET.findall(data)
print url
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
print url
if url == "/favicon.ico":
return self.decompress_img(self.Pages.favico())
else :
return self.decompress_html(self.Pages.root())
if __name__ == "__main__":
swww = Serverhttp()
swww.start()
ssmtp = Serversmtp()
ssmtp.start()
sendmail("test#test.com","b#gmail.com","hello")
print "toto"
Regards and thanks all people
it was better to use : SocketServer.BaseRequestHandler with handler
and one for each server :
as seen here :
# MetaProject v 0.21
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
import threading
import SocketServer
SocketServer.TCPServer.allow_reuse_address = True
"""
Thanks to :
People from irc :
Flox,Luyt
People from stack Overflow (http://stackoverflow.com/):
Philippe Leybaert,Platinum Azure,methodin,Suresh Kumar,S.Lott,MatTheCat,
kevpie,Ignacio Vazquez-Abrams,adamk,Frédéric Hamidi,THC4k,THC4k,Blam,bstpierre
"""
def sendmail(exp,dest,msg):
server = dest.split("#")[1]
s = smtplib.SMTP("localhost")
s.sendmail(exp,dest,msg)
#contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Serversmtp(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
return "toto"
class Pages :
def __init__(self):
self.balisep = re.compile("<\?.*\?>",re.DOTALL)
def root(self,cgi=None):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrJhECbpCKgWGZuukJxUbKtUlpiWWZyfp4ekFCyg8jZcxUUZeaVKCiV
5JfkK2krgUSVuOztuLhs9CFm2eiDjQYAG5wecg==""")
def faviconico(self):
return self.decompress_img("""eNqdk39MVWUYx99zDrZkJJc/d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TeH8kUqxlGQ0miCv8KT2aZqTWsNU03yl
RjR3s6H+93C5/wIoQoi6""")
def toto(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04yrLLy1WSC1JLVZIVCjJL8nnstGHSNjog9UBAGolDzo=""")
def p404(self):
return self.decompress_html("""eNqzySjJzbHjsknKT6m04zIxMFFIScwrVihJVEhLTE5VUOSy0YdI2eiDVQIAZBgOeA==""")
def decompress_img(self,img):
img = zlib.decompress(base64.decodestring(img))
return img
def decompress_html(self,html) :
page = "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n"
page+=zlib.decompress(base64.decodestring(html))
commands = self.balisep.findall(page)
print commands
for c in commands :
command = c.replace("<? ","")
command = c.replace("<?","")
command = command.replace(" ?>","")
command = command.replace("?>","")
print command
with stdoutIO() as s:
exec(command)
page = page.replace(c,s.getvalue())
return page
class Serverhttp(SocketServer.BaseRequestHandler):
def handle(self):
self.Pages = Pages()
self.GET = re.compile("GET.*?HTTP")
self.POST = re.compile("POST.*?HTTP")
self.data = self.request.recv(1024)
socket = self.request
print "%s wrote:" % self.client_address[0]
self.data = self.traitement(self.data)
socket.sendto(self.data, self.client_address)
def traitement(self,data):
url = self.POST.findall(data)
url = self.GET.findall(data)
url = url[0].replace("GET","")
url = url.replace("POST","")
url = url.replace("HTTP","")
url = url.replace(" ","")
url = re.sub(r"^/","",url)
url = re.sub(r"\.","",url)
if url != "":
urls = url.split("/")
if len(urls) != 0 :
print urls
url = urls[0]
print "url %s"%url
if url == "" :
return self.Pages.root()
elif url in dir(self.Pages) and url != "":
return getattr(self.Pages,url)()
else :
return self.Pages.p404()
def serve_thread(host, port):
if port == 4242 :
server = SocketServer.TCPServer((host, port), Serverhttp,bind_and_activate=True)
elif port == 25 :
server = SocketServer.TCPServer((host, port), Serversmtp,bind_and_activate=True)
server.serve_forever()
if __name__ == "__main__":
threading.Thread(target=serve_thread,args=('localhost', 4242)).start()
threading.Thread(target=serve_thread,args=('localhost', 25)).start()
print "toto"
Related
everyone.
I send data to the server, it eats them, and then I start waiting for a response from the server by the client, and at this moment both the server and the client hang, but if you send data to the server without waiting for a response from it, it will calmly perform the function without freezes.
Who knows what the problem is?
client
import os
import socket
from time import sleep
import ast
class socker:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('localhost', 4545))
def send_request(self, request):
# self.sock.settimeout(5)
self.sock.send(request)
def recieve_request(self):
byte = b""
while True:
data = self.sock.recv(1024)
byte += data
if not data:
break
return byte
def close_connection(self):
self.sock.close()
def test():
s = socker()
s.send_request(str({"request": "get_files_list"}).encode())
s.recieve_request()
test()
server
import socket
import ast
import os
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 4545))
print("Сервер включён!")
while True:
try:
server.listen(10)
conn, addr = server.accept()
print('Подключён:', addr)
byte = b""
while True:
data = conn.recv(1024)
byte += data
if not data:
break
data = ast.literal_eval(byte.decode())
request = data["request"]
print("Запрос: ", request)
if request == "get_info_about_file":
pass
elif request == "get_files_list":
files = os.walk(saved_dir)
dirpaths = []
file_names = []
for dirpath, dirnames, filenames in files:
dirpaths.append(dirpath)
print(dirpath)
for file in filenames:
file_names.append(os.path.join(dirpath, file))
conn.send(str({"dirs": dirpaths, "files": file_names}).encode())
conn.shutdown(socket.SHUT_RDWR)
except KeyboardInterrupt:
server.close()
except Exception as err:
print(err)
if __name__ == "__main__":
start_server()
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
husainshoab#hs-Len:~$ python IOTDeviceSocket.py
Traceback (most recent call last):
File "IOTDeviceSocket.py", line 7, in
class ClientSocket:
File "IOTDeviceSocket.py", line 11, in ClientSocket
self.soc = None
NameError: name 'self' is not defined
There appears to be nothing wrong with your code. I just used it to create a simple test application
# ClientSocket.py
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
cs = ClientSocket()
cs.start_client()
cs.send_to_Server('Hello')
cs.receive_from_Server()
here's a simple test server which just spits back some JSON data
# test_server.py
import socket
from datetime import datetime
import json
def logMessage(clientMessage):
logTime = datetime.today();
msg = "{} | {}\n".format(logTime, clientMessage)
print msg
TCP_PORT = 8000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', TCP_PORT))
# listen() puts the socket into server mode,
server.listen(1)
while True:
# wait for an incoming connection
connection, address = server.accept()
try:
# receive data in chunks of 64 bytes
while True:
data = connection.recv(64)
# how do we know if we received all the data?
if data:
# we received data from the client, log it to the file
logMessage(data)
response = {
'name' : 'Jonathan Swift',
'occupation' : 'author'
}
jsonResponse = json.dumps(response)
messageLength = len(jsonResponse)
bytesSent = 0
# send a response to the client after turning our dict into
# a JSON string
while(bytesSent < messageLength):
sent = connection.send(jsonResponse)
bytesSent += sent
else:
# no data, break out of receiving loop
break
except Exception as e:
raise
finally:
connection.close()
import socket
MAX_BUFFER_SIZE = 4096
class ClientSocket:
soc = None
def __init__(self):
print("Client socket started....")
self.soc = None
def send_to_Server(self, data):
print('Time to send data to Server..... %s', data)
self.soc.send(data.encode("utf8"))
def receive_from_Server(self):
print('Time to receive from Server.....')
result_bytes = self.soc.recv(MAX_BUFFER_SIZE)
result_string = result_bytes.decode("utf8")
print("Result from server is {}".format(result_string))
def start_client(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect(("localhost", 8000))
print('Client connected....')
you should define the soc variable after class statement so that you can use it globally.
Well, I'm trying to make a simple Network TCP chatting program to dive deeper in python, threading and networking. The program worked but with just one user, I looked this up, I found that I need threading to make the server accept more than one user. I threaded the server but now when you connect the second user it disconnect the first one. Source code may not be that good..
#!/usr/bin/python
import socket, sys, threading
from time import sleep
# Global Stuff
localhost = socket.gethostbyname(socket.gethostname())
#localhost = '192.168.x.x'
serverPort = 5003
buffer = 1024 #Bytes
backlog = 5
userThread= []
count = 0
class server(object):
''' Constructor to Establish Bind server once an object made'''
def __init__(self, localhost, serverPort): # Connect Tcp
global backlog, count
self.servSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.servSock.bind((localhost, serverPort))# bind((host,Port))
self.servSock.listen(backlog)
print count
except Exception, e:
print "[Bind ]", e
sys.exit()
def accept(self):
global userThread, conn, addr, count
"""
- PROBLEM IS IN HERE SOMEWHERE SERVER DOESN'T ADD THE OTHER CLIENT EXCEPT ONCE.
- THREAD DOEN'T KEEP THE CLIENT.
- THE SECOND CLIENT FREEZES WHILE SENDING THE VERY FIRST MESSAGE TILL THE FIRST
CLIENT SEND A MESSAGE THEN IT CAN SEND MESSAGES AND THE FIRST CLIENT CAN'T SEND SHIT.
"""
count+=1
while True:
print count
self.conn, self.addr = self.servSock.accept()
conn = self.conn
print("This is a connection: ", conn)
#acceptThread = threading.start_new_thread(target=serverObj.accept, args=(conn))
#addr = self.addr
print "[Listening..]"
if(self.addr not in userThread):
userThread.append(self.addr)
print "Client's added Successfully"
else:
pass
def redirect(self):
global buffer, userThread, conn, count
count+=1
while True:
try:
print "Redirecting " + str(count)
self.data = conn.recv(buffer)
if self.data:
for user in userThread:
#conn.send(b'Recieved by server!\n')
conn.sendto("Sent!\n"+self.data+"\n", user)
print "Server: Data sent[" +self.data+"] to ["+str(user)+"]"
else:
self.data = conn.recv(buffer)
print "No dataa found"
except Exception, e:
print "[Redirect ] ",e
sleep(7)
print "OUT"# testing if it's getting out this infinite loop.
def exit(self):
self.server.close()
def main():
global localhost, serverPort, conn
try:
serverObj = server(localhost, serverPort)
print("[+] Server is UP!")
except Exception, e:
print "[Main ] ",e
exit()
acceptThread = threading.Thread(name = "Accepting Connections", target=serverObj.accept)
redirThread = threading.Thread(name = "Redirecting Data", target=serverObj.redirect)
acceptThread.start()
redirThread.start()
print userThread
main()
######################################### Client ##########################################
#!/usr/bin/python
# This is client file
"""
http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python
https://docs.python.org/2/library/threading.html
"""
import socket
import threading
from time import sleep
# Client Info
#clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#localhost = '192.168.x.x'
# Global Stuff
serverIP = socket.gethostbyname(socket.gethostname())
#serverIP = '192.168.x.x'
serverPort, MsgSendError, MsgSendSucc, clientPort, data, buffer =\
5003, False, True, 12345, '',1024 #Bytes
class client(object):
global MsgSendError, MsgSendSucc, buffer, data
''' Constructor to Establish Connection once client is up'''
def __init__(self, serverIP, serverPort): # Connect Tcp
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.sock.connect((serverIP, serverPort))
except Exception, e:
return "[Connecting to Server]", e
def send(self, data):
try:
self.sock.send(data) # covnert it from string into byte streams to be in proper format.
#print str(data)
return MsgSendSucc
except:
return MsgSendError
def receive2(self):
try:
data = self.sock.recv(buffer)
#print "Function: Receive2."# testing
#print(str(data))# testing
#print "Received!"# testing
return str(data)
except Exception, e:
return "[In receive2]", e
def main():
global serverIP, serverPort, data#, sock
clientObj = client(serverIP, serverPort)
alias = raw_input("Your Name USER! ")
sentData = ''
while sentData is not 'Quit':
sentData = raw_input("Data>> ")
data = alias + ": "+sentData
if clientObj.send(data) == MsgSendSucc:
#print "Sent!"
#print "Fetching..\n"# testing
print(clientObj.receive2())
# testing
main()
I'm trying to create a small, multithreaded proxyscript that allows me to proxy LDAP requests and manipulate the results (like adding extra fields, renaming them etc).
In the example below, I try to replace the field 'TEST' by 'DONE'. Is there any solution to allow this socketstream to be manipulated? Should I decode it somewhat first?
import select
import socket
import sys
import threading
import signal
import re
import random
import time
import binascii
from ldaptor.protocols import pureldap, pureber
from time import gmtime, strftime
ASTLDAP_PROXY_PORT = 1389
ASTLDAP_HOST = 'localhost'
ASTLDAP_PORT = 389
BUFFERSIZE = 1024
DELAY = 0.0001
class Forward:
def __init__(self):
self.forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def start(self, host, port):
try:
self.forward.connect((host, port))
return self.forward
except Exception, e:
print e
return False
class AstLdapProxyServer(threading.Thread):
input_list = []
channel = {}
def __init__(self, host, port, socket):
threading.Thread.__init__(self)
self.host = host
self.port = port
# Socket ontvangen die we meekregen bij nieuwe thread.
self.socket = socket
print "[+] New thread started for "+host+":"+str(port)
self.socket.bind((host, port))
self.socket.listen(200)
def register_signals(self):
signal.signal(signal.SIGHUP, self.signal_handler)
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGQUIT, self.signal_handler)
def main_loop(self):
self.input_list.append(self.socket)
while 1:
#time.sleep(DELAY)
ss = select.select
inputready, outputready, exceptready = ss(self.input_list, [], [])
for self.s in inputready:
if self.s == self.socket:
self.on_accept()
break
self.data = self.s.recv(BUFFERSIZE)
if len(self.data) == 0:
self.on_close()
else:
self.on_recv()
def on_accept(self):
forward = Forward().start(ASTLDAP_HOST, ASTLDAP_PORT)
clientsock, clientaddr = self.socket.accept()
if forward:
print clientaddr, "has connected"
self.input_list.append(clientsock)
self.input_list.append(forward)
self.channel[clientsock] = forward
self.channel[forward] = clientsock
else:
print "Can't establish connection with remote server.",
print "Closing connection with client side", clientaddr
clientsock.close()
def on_close(self):
print self.s.getpeername(), "has disconnected"
#remove objects from input_list
self.input_list.remove(self.s)
self.input_list.remove(self.channel[self.s])
out = self.channel[self.s]
# close the connection with client
self.channel[out].close() # equivalent to do self.s.close()
# close the connection with remote server
self.channel[self.s].close()
# delete both objects from channel dict
del self.channel[out]
del self.channel[self.s]
def on_recv(self):
data = self.data
# Manipulate result
output = re.sub(r'uzgEmail1', r'TEST', data)
# Send result to client (DOESN'T WORK)
self.channel[self.s].send(output)
# Send result to client (WORKS when I disable send above)
self.channel[self.s].send(data)
if __name__ == '__main__':
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
server = AstLdapProxyServer(ASTLDAP_HOST, ASTLDAP_PROXY_PORT, tcpsock)
server.start()
try:
server.main_loop()
except KeyboardInterrupt:
sys.exit(1)
This is the code that I have used.But I don't get actual result that I want.When I execute code ChatServer file works properly,but ChatClient gives only one line(Usage : python telnet.py hostname port).Please Help me.I am new in python.
The server code:
#!/usr/bin/env python
#!/usr/bin/env python
"""
A basic, multiclient 'chat server' using Python's select module
with interrupt handling.
Entering any line of input at the terminal will exit the server.
"""
import select
import socket
import sys
import signal
from communication import send, receive
BUFSIZ = 1024
class ChatServer(object):
""" Simple chat server using select """
def __init__(self, port=3490, backlog=5):
self.clients = 0
# Client map
self.clientmap = {}
# Output socket list
self.outputs = []
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(('',port))
print 'Listening to port',port,'...'
self.server.listen(backlog)
# Trap keyboard interrupts
signal.signal(signal.SIGINT, self.sighandler)
def sighandler(self, signum, frame):
# Close the server
print 'Shutting down server...'
# Close existing client sockets
for o in self.outputs:
o.close()
self.server.close()
def getname(self, client):
# Return the printable name of the
# client, given its socket...
info = self.clientmap[client]
host, name = info[0][0], info[1]
return '#'.join((name, host))
def serve(self):
inputs = [self.server,sys.stdin]
self.outputs = []
running = 1
while running:
try:
inputready,outputready,exceptready = select.select(inputs, self.outputs, [])
except select.error, e:
break
except socket.error, e:
break
for s in inputready:
if s == self.server:
# handle the server socket
client, address = self.server.accept()
print 'chatserver: got connection %d from %s' % (client.fileno(), address)
# Read the login name
cname = receive(client).split('NAME: ')[1]
# Compute client name and send back
self.clients += 1
send(client, 'CLIENT: ' + str(address[0]))
inputs.append(client)
self.clientmap[client] = (address, cname)
# Send joining information to other clients
msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client))
for o in self.outputs:
# o.send(msg)
send(o, msg)
self.outputs.append(client)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
else:
# handle all other sockets
try:
# data = s.recv(BUFSIZ)
data = receive(s)
if data:
# Send as new client's message...
msg = '\n#[' + self.getname(s) + ']>> ' + data
# Send data to all except ourselves
for o in self.outputs:
if o != s:
# o.send(msg)
send(o, msg)
else:
print 'chatserver: %d hung up' % s.fileno()
self.clients -= 1
s.close()
inputs.remove(s)
self.outputs.remove(s)
# Send client leaving information to others
msg = '\n(Hung up: Client from %s)' % self.getname(s)
for o in self.outputs:
# o.send(msg)
send(o, msg)
except socket.error, e:
# Remove
inputs.remove(s)
self.outputs.remove(s)
self.server.close()
if __name__ == "__main__":
ChatServer().serve()
The chat client:
#! /usr/bin/env python
"""
Simple chat client for the chat server. Defines
a simple protocol to be used with chatserver.
"""
import socket
import sys
import select
from communication import send, receive
BUFSIZ = 1024
class ChatClient(object):
""" A simple command line chat client using select """
def __init__(self, name, host='127.0.0.1', port=3490):
self.name = name
# Quit flag
self.flag = False
self.port = int(port)
self.host = host
# Initial prompt
self.prompt='[' + '#'.join((name, socket.gethostname().split('.')[0])) + ']> '
# Connect to server at port
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, self.port))
print 'Connected to chat server#%d' % self.port
# Send my name...
send(self.sock,'NAME: ' + self.name)
data = receive(self.sock)
# Contains client address, set it
addr = data.split('CLIENT: ')[1]
self.prompt = '[' + '#'.join((self.name, addr)) + ']> '
except socket.error, e:
print 'Could not connect to chat server #%d' % self.port
sys.exit(1)
def cmdloop(self):
while not self.flag:
try:
sys.stdout.write(self.prompt)
sys.stdout.flush()
# Wait for input from stdin & socket
inputready, outputready,exceptrdy = select.select([0, self.sock], [],[])
for i in inputready:
if i == 0:
data = sys.stdin.readline().strip()
if data: send(self.sock, data)
elif i == self.sock:
data = receive(self.sock)
if not data:
print 'Shutting down.'
self.flag = True
break
else:
sys.stdout.write(data + '\n')
sys.stdout.flush()
except KeyboardInterrupt:
print 'Interrupted.'
self.sock.close()
break
if __name__ == "__main__":
import sys
if len(sys.argv)<3:
sys.exit('Usage: %s chatid host portno' % sys.argv[0])
client = ChatClient(sys.argv[1],sys.argv[2], int(sys.argv[3]))
client.cmdloop()
###############################################################################
# The communication module (communication.py)
###############################################################################
import cPickle
import socket
import struct
marshall = cPickle.dumps
unmarshall = cPickle.loads
def send(channel, *args):
buf = marshall(args)
value = socket.htonl(len(buf))
size = struct.pack("L",value)
channel.send(size)
channel.send(buf)
def receive(channel):
size = struct.calcsize("L")
size = channel.recv(size)
try:
size = socket.ntohl(struct.unpack("L", size)[0])
except struct.error, e:
return ''
buf = ""
while len(buf) < size:
buf = channel.recv(size - len(buf))
return unmarshall(buf)[0]