티스토리 뷰

Server :
from random import randrange as baserand
import random
import socket

HOST = "192.168.8.1"
PORT = 6000

mysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mysocket.bind((HOST, PORT))
hosts = []
gamedic = {"NONE":"NONE"}

while 1:
    print "Listening...\n"
    packet, address = mysocket.recvfrom(1024)
    
    print "Connect hosts : ",hosts
    print "Packet recevied"
    print "From : %s, port : %s"%(address[0],address[1])
    print "Length : ",len(packet)
    print "Content : ",packet
    ball = strike = 0

    if not(hosts.count(address)):
        hosts.append(address)
        balls = [1,2,3,4,5,6,7,8,9]
        random.shuffle(balls)
        gamedic[address] = [1,balls]
        packet = "===BaseBall Game===\n"
        packet += "GAME START!!\n\n"
    elif (packet == "quit"):
        mysocket.sendto("quit",address)
        hosts.remove(address)

        if not(len(hosts)):break
    else:
        if len(packet) != 3:
            packet = "Wrong input!"
        else:
            gamestat = gamedic[address]
            gamenet = []
            try:
                for x in range(3):
                    gamenet.append(int(packet[x]))
                for x in range(3):
                    for y in range(3):
                        if gamestat[1][x] == gamenet[y]:
                            if x==y:
                                strike += 1
                            else:
                                ball += 1
                packet = "%d strike, %d ball!!"%(strike,ball)
                gamestat[0] += 1
            except ValueError:
                packet = "Wrong input!"

    mysocket.sendto(packet,address)

    if strike == 3:
        hosts.remove(address)
        if not(len(hosts)):break

print gamedic
mysocket.close()


Client :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import socket
 
HOST = "192.168.8.1"
PORT = 6000
 
mysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = (HOST,PORT)
packet = "Game start connection!!"
mysocket.sendto(packet,address)
while 1:
    packet, address = mysocket.recvfrom(1024)
    print packet
    if packet[0] == '3':
        break
    if packet == "quit":
        break
    string = raw_input("Any integer >>>")
 
    mysocket.sendto(string,address)
 
mysocket.close()

Server측 프로그램에 2주동안 배운 파이선의 내용들을 대부분 짜집기 해서 억지로 나마 만들어 보왔다. 서버의 종료 조건은 전의 데이타 그램 형식과 비슷하고, 여러개의 클라이언트가 서버에 접속해 야구게임을 수행할 수 있다.

여기다가 Shelve 모듈을 이용하여 파일과 연동하면, 등수까지 지정할 수 있다.
댓글
댓글쓰기 폼