如何在Python套接字中创建ping客户端?

时间:2014-12-25 22:31:54

标签: python sockets

我学习Python并且作为练习决定为网络游戏“Backgammon”编写服务器。出现的问题是确保在队列apponet中找到的仍然在线?如何发送ping并接受答案?我试图在71行上做,但这是不正确的。

import pymongo, socket, threading, string, json, MySQLdb, random, time
stat = True
conn = {}
#gamers = {}
games = {}
diceroll = []
tempconn = {}

c = pymongo.Connection()
db = c.nardy
nru = db.notregusers
uwait = db.userwait

class ClientThread(threading.Thread):

    def __init__(self, channel, details):
        self.channel = channel
        self.details = details
        threading.Thread.__init__(self)

    def getUserId(self, data):
        json_data = json.loads(data)
        if json_data['t'] == 'n':
            print ' - User not register'
            if nru.find({'identuser':json_data['i'], 'platform':json_data['p']}).count() == 0:
                print ' - New user'
                count = nru.find().count();
                newid = count + 1;
                nru.save({'id':newid, 'identuser':json_data['i'], 'platform':json_data['p'], 'level':1})
                return nru.find_one({'id':newid})
            else:
               print ' - Old user'
               return nru.find_one({'identuser':json_data['i'], 'platform':json_data['p']})
        elif json_data['t'] == 'r':
            return 9999

    def mySQLConnect(self):
        db = MySQLdb.connect(host="localhost", user="", passwd="", db="", charset='utf8')
        return db

    def run(self):
        while True:
            data = self.channel.recv(1024)
            try:
                json_data = json.loads(data)                
                comm = json_data['c']
                if comm == 'x':
                    if conn.has_key(gamer['level']) and self in conn[gamer['level']]:
                        conn[gamer['level']].remove(self)
                    self.channel.close()
                    break
                elif comm == 'h':
                    gamer = self.getUserId(data)
                    self.gamer = gamer
                elif comm == 'f':
                    lev = 0
                    findenemy = 1
                    while findenemy == 1:
                        if conn.has_key(gamer['level']):
                            lev = gamer['level']
                        elif conn.has_key((gamer['level'] - 1)):
                            lev = (gamer['level'] - 1)
                        elif conn.has_key((gamer['level'] + 1)):
                            lev = (gamer['level'] + 1)
                        if lev != 0:
                            if len(conn[lev]) > 0:
                                enemy = conn[lev].pop(0)
                                firsttime = time.time()
                                enemy.channel.send('{"o":"p"}')

                                while (firsttime + 30) > time.time() and findenemy == 1:
                                    if comm == 'k':
                                        findenemy = 0
                                        print ' - Ping enemy: ok'


                                if findenemy == 0:
                                    self.enemy = enemy
                                    gameid = str(self.gamer['id']) + '_' + str(self.enemy.gamer['id'])
                                    games[gameid] = {'dice':[], 'nextstep':0}
                                    vrag = self.enemy
                                    a = random.sample(range(1,7),2)
                                    self.channel.send('{"o":"s", "u":"' + str(a[0]) + '", "e":"' + str(a[1]) + '"}')
                                    vrag.channel.send('{"o":"s", "u":"' + str(a[1]) + '", "e":"' + str(a[0]) + '"}')
                                    if a[0] > a[1]:
                                        step = 1
                                        games[gameid]['nextstep'] = self.gamer['id']
                                        self.channel.send('{"o":"u"}')
                                        vrag.channel.send('{"o":"w"}')
                                    else:
                                        step = 2
                                        games[gameid]['nextstep'] = self.enemy.gamer['id']
                                        self.channel.send('{"o":"w"}')
                                        vrag.channel.send('{"o":"u"}')
                                    tempconn[self.enemy] = self
                            else:
                                conn[lev].append(self)
                                findenemy = 0
                                self.channel.send('{"o":"q"}')
                        else:
                            conn[gamer['level']] = [self]
                            self.channel.send('{"o":"q"}')
                elif comm == 'w':
                    if not hasattr(self, 'enemy'):
                        self.enemy = tempconn[self]
                        vrag = self.enemy
                        gameid = str(self.enemy.gamer['id']) + '_' + str(self.gamer['id'])
                    self.channel.send('{"o":"o"}')
                elif comm == 'r' and games[gameid]['nextstep'] == self.gamer['id']:
                    dice = []
                    dice.append(self.gamer['id'])
                    dice.append(random.randint(1,6))
                    dice.append(random.randint(1,6))
                    games[gameid]['dice'].append(dice)
                    self.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
                    vrag.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
                    games[gameid]['nextstep'] = self.enemy.gamer['id']
                elif comm == 'r' and games[gameid]['nextstep'] != self.gamer['id']:
                    self.channel.send('{"o":"w"}')
                elif comm == 'm' and 't' in json_data:
                    self.channel.send('{"o":"y", "t":"' + str(json_data['text']) + '"}')
                    vrag.channel.send('{"o":"e", "t":"' + str(json_data['text']) + '"}')
                elif comm == 's':
                    self.channel.send('{"o":"g", "countgame":"' + str(len(games)) + '"}')
                elif comm == 'q' and 's' in json_data and 'e' in json_data:
                    print " - Player step"
                elif comm == 'b' and self in conn[gamer['level']]:
                    conn[gamer['level']].remove(self)

            except ValueError:
                continue
        print 'Closed connection:', self.details[0]

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8088))
server.listen(5)

while stat:
    channel, details = server.accept()
    ClientThread(channel, details).start()

也许,除了回答这个问题之外,你还给我一些建议......

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式发送ping并获得响应。

  1. 使用scapy。使用sendp函数发送ping并获得响应。
  2. 使用os.system调用命令行发送ping并获取响应。与os.system('ping 127.0.0.1')
  3. 一样

    希望它有所帮助。:)