|
이전 질문 게시판은 새 글 쓰기를 막았습니다. [질문 게시판]을 이용바랍니다.
Date |
2011/06/06 20:16:34 |
Name |
황신 |
Subject |
파이썬(프로그래밍)질문드립니다 |
클라이언트
import socket
import threading
import sys
class MyClient(threading.Thread):
def run(self):
while 1:
self.recvMessage()
def connectToServer(self):
self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host='localhost'
port=4020
self.sock.connect((host, port))
recvdata = self.sock.recv(1000000).decode('UTF-8')
name = input(recvdata.lstrip('4|'))
sendMsg = name + '\n'
self.sock.send(bytes(sendMsg, 'UTF-8'))
recvdata = self.sock.recv(1000000).decode('UTF-8')
m = recvdata.lstrip('4|')
if m.strip() != 'ok':
exit()
self.start() # start new thread
while 1:
############## To Do ##############
def recvMessage(self):
############## To Do ##############
if __name__ == '__main__':
client = MyClient()
client.connectToServer()
서버
import socket
from socketserver import ThreadingTCPServer, StreamRequestHandler
import threading
#lock = threading.allocate_lock()
lock = threading.Lock()
PORT = 4020
class Subscriber(object):
def __init__(self, parent, name=''):
self.parent = parent
self.name = name
self.sock = parent.request
def setName(self, name):
self.name = name
def getName(self):
return self.name
def upload(self, msg):
self.getParent().publisher.handleMessage(self, msg)
def send(self, msg):
self.parent.request.sendall(bytes(msg,'UTF-8'))
def close(self):
self.parent.request.shutdown(socket.SHUT_RD | socket.SHUT_WR)
self.parent.request.close()
def getParent(self):
return self.parent
class Publisher(object):
def __init__(self):
self.subscribers = {}
def addUser(self, user):
if user.getName() in self.subscribers:
user.send('5|The name is already registered\n')
return False
lock.acquire()
self.subscribers[user.getName()] = user
lock.release()
#self.broadcastMessage('['+user.getName()+']' + ' entered.\n')
user.send('4|ok\n')
print ('%s joined' % user.getName())
print (len(self.subscribers), 'connections.')
return True
def removeUser(self, name):
if name not in self.subscribers:
return False
user = self.subscribers[name]
# user.send('Connection closed\n')
user.close()
user.getParent().connectedFlag = False
lock.acquire()
del self.subscribers[name]
lock.release()
# self.broadcastMessage('['+name+']' + ' left.\n')
print ('%s left' %name)
print (len(self.subscribers), 'connections')
return True
def handleMessage(self, user, msg):
if not msg.strip():
return
print ('receive message from ', user.getName(), ' : ', msg)
if msg.startswith('0'):
self.sendSubsList(user)
elif msg.startswith('2'):
self.sendAnotherSub(user, msg)
elif msg.startswith('6'):
self.removeUser(user.getName())
else:
print ('Invalid command: ' , user.getName())
def broadcastMessage(self, msg):
for user in self.subscribers.values():
user.send(msg)
def sendSubsList(self, user):
l = '1|'
for u in self.subscribers.values():
l = l + u.getName() + '|'
l = l + '\n'
user.send(l)
def sendAnotherSub(self, user, msg):
m = msg.lstrip('2|')
receiver = m.split('|')[0]
print ('receiver: ', receiver)
if receiver not in self.subscribers:
errMsg = '5|' + receiver + ' is not logging on\n'
print (errMsg)
user.send(errMsg)
return
sendMsg = '3|'+user.getName()+'|'+m.split('|')[1]
print (sendMsg)
print (self.subscribers[receiver].getName())
self.subscribers[receiver].send(sendMsg)
def action_quit(self, name, args):
return self.removeUser(name)
class ChatRequestHandler(StreamRequestHandler):
publisher = Publisher()
def handle(self):
print ('connection from', self.client_address)
try:
user = self.readAndRegisterName()
if not user: raise Exception
self.connectedFlag = True
data = self.rfile.readline().decode('UTF-8')
while data:
user.upload(data)
if not self.connectedFlag:
break
data = self.rfile.readline().decode('UTF-8')
except socket.error:
print ('Socket Error')
except Exception:
print ('User Excetion')
print ('Disconnected from ', self.client_address)
try:
self.publisher.removeUser(user.getName())
except:
pass
def readAndRegisterName(self):
user = Subscriber(self)
while 1:
user.send('4|Enter your name.\n')
try:
name = self.rfile.readline().decode('UTF-8').strip()
except socket.error:
print ('User Socket Error.')
user.close()
return
if not name or name.startswith('/'):
user.send('5|Wrong name.\n')
continue
user.setName(name)
if self.publisher.addUser(user):
return user
class ChatServer(ThreadingTCPServer):
allow_reuser_address = True
if __name__ == '__main__':
ChatServer.allow_reuse_address = True
server = ChatServer(("", PORT), ChatRequestHandler)
print ('listening on port ', PORT)
server.serve_forever()
이런 서버와 클라이언트가주어졌을때
메신져 프로그램을 짜는 문제인데요..
예를들면 hello를 쳤을때 상대방이답이와야한다던지 해야합니다
도움주실분계신가요
|
통합규정 1.3 이용안내 인용
"Pgr은 '명문화된 삭제규정'이 반드시 필요하지 않은 분을 환영합니다.
법 없이도 사는 사람, 남에게 상처를 주지 않으면서 같이 이야기 나눌 수 있는 분이면 좋겠습니다."
|