资源简介

python多人聊天服务器,供新人学习socket用,适合flash,actionscript

资源截图

代码片段和文件信息

#!/usr/bin/python
#-*- coding: utf-8 -*-

import socket

host = “127.0.0.1“
port = 9921
addr = hostport
clients = {}

def stringPolishing(value):
    length = 6-len(value)
    for i in range(length):
        value = ‘0‘+value
    return value

def decoderData(valuesock):
    position = 0
    print value

    try:
        commandLen = int(value[0:6])
        position += 6
        command = value[position:position+commandLen]
        print ‘command‘command
        position += commandLen

        if command==“login“:
            nameLen = int(value[position:position+6])
            position += 6
            userName = value[position:position+nameLen]
            print ‘userName‘+userName
            sendData = ‘‘
            for key in clients.keys():
                sendData += stringPolishing(str(len(key)))
                sendData += key
                clients[key].send(‘000005login‘+stringPolishing(str(nameLen))+userName)
            sock.send(‘000010currPeople‘+stringPolishing(str(len(clients)))+sendData)
            clients[userName] = sock
        elif command==“talk“:
            for key in clients.keys():
                clients[key].send(value)
        elif command==“logout“:
            nameLen = int(value[position:position+6])
            position += 6
            userName = value[position:position+nameLen]
            clients[userName].close()
            del clients[userName]
            for key in clients.keys():
                clients[key].send(value)
    except ValueError:
        sock.send(“command error“)

server = socket.socket(socket.AF_INETsocket.SOCK_STREAM)
server.bind(addr)
server.listen(999)

while True:
    clientSockaddrs = server.accept()
    
    print “client ip:“ + str(addrs[0])
    print “client port:“ + str(addrs[1])

    clientData = clientSock.recv(2000)
    decoderData(clientDataclientSock)

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件      51962  2010-11-25 18:33  聊天程序协议.pdf

     文件        647  2010-11-03 21:40  policyServer.py

     文件       1927  2010-11-25 20:13  ChatServer.py

----------- ---------  ---------- -----  ----

                54536                    3


评论

共有 条评论