Python 2.7 Python2.7套接字发送到不';行不通

Python 2.7 Python2.7套接字发送到不';行不通,python-2.7,sockets,Python 2.7,Sockets,我不熟悉插座。基本上我有一个套接字服务器。客户机本身是一个移动方块,它将坐标发送到服务器。当我将两个客户端连接到服务器时,我会将它们保存为自动生成的端口,并根据接收到的数据将coords发送到另一个客户端(它们之间交换coords),以便将来可以制作多人游戏 问题是在打印行中 打印“%s->%s”%(反序列化的对象IP,发送到) 它显示映射是正确的。但当我移动方块并打印接收到的数据时,它会写入自己的坐标,而另一个客户端的控制台不会受到影响 你觉得怎么样?使用这种方法是否可以实现这一目标 下面是套

我不熟悉插座。基本上我有一个套接字服务器。客户机本身是一个移动方块,它将坐标发送到服务器。当我将两个客户端连接到服务器时,我会将它们保存为自动生成的端口,并根据接收到的数据将coords发送到另一个客户端(它们之间交换coords),以便将来可以制作多人游戏

问题是在打印行中

打印“%s->%s”%(反序列化的对象IP,发送到)

它显示映射是正确的。但当我移动方块并打印接收到的数据时,它会写入自己的坐标,而另一个客户端的控制台不会受到影响

你觉得怎么样?使用这种方法是否可以实现这一目标

下面是套接字服务器:

import socket
import sys
import cPickle
from thread import *
from models.player import Player

HOST = ''   
PORT = 8888 

connected = []

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

# start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #infinite loop so that function do not terminate and thread do not end.
    while True:
        #Receiving from client
        data = conn.recv(4096)
        if not data: 
            break
        deserialized_obj = cPickle.loads(data)
        #print deserialized_obj
        if data and len(connected) > 1:
            sendTo =  connected[1] if deserialized_obj.IP[1] == connected[0] else connected[0]

            print "%s -> %s " % (deserialized_obj.IP, sendTo)
            print "sendto", sendTo
            conn.sendto(cPickle.dumps(deserialized_obj), ('localhost', sendTo))
        else:
            conn.sendall("second player needed")
    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    connected.append(addr[1])
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))
s.close()   
客户:

import pygame
import socket
import sys
import pickle
from models.player import Player

pygame.init()

gameDisplay = pygame.display.set_mode((800,600))

gameExit = False

player_height = 20
player_width = 10;

lead_x = 300 
lead_y = 300

lead_x_change = 0

jump_aggr = 5
jump_max_height = player_height * 2
jump_curr_pos = 0
jumping = False

clock = pygame.time.Clock()

#######

#create an INET, STREAMing socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()

print 'Socket Created'

host = 'localhost'
port = 8888

#Connect to remote server
s.connect((host , port))

print 'Socket Connected to ' + host

socketIp = s.getsockname()
player = Player(lead_x, lead_y, socketIp)

all_players = [player]

########

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if jump_curr_pos == 0:
                    jumping = True
            if event.key == pygame.K_d:
                lead_x_change += 5
            elif event.key == pygame.K_a:
                lead_x_change -= 5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_d or event.key == pygame.K_a:
                lead_x_change = 0

    if jumping:
        jump_curr_pos += jump_aggr
        # check for next frame
        if jump_curr_pos + jump_aggr >= jump_max_height:
            jumping = False
            jump_curr_pos -= jump_aggr
    else:
        if jump_curr_pos > 0:
            jump_curr_pos -= jump_aggr
        else:
             jump_curr_pos = 0

    player.X += lead_x_change
    player.Y -= jump_curr_pos if jumping else -jump_curr_pos

    gameDisplay.fill((255,255,255))

    # print lead_x, " ", lead_y
    # print s.getsockname()

    #####
    try :
        serialized_obj = pickle.dumps(player)
        s.sendall(serialized_obj)
    except socket.error:
        #Send failed
        print 'Send failed'
        sys.exit()

    #Now receive data
    reply = s.recv(1024)
    #Here it prints its own coordinates, but not the other client's one
    print reply
    pygame.draw.rect(gameDisplay, (0,0,0),[player.X,player.Y, player_width, player_height])
    pygame.display.update()

    clock.tick(30)

pygame.quit()
quit()
和播放器型号:

class Player:
    def __init__(self, x, y, ip):
        self.X = x
        self.Y = y
        self.IP = ip

    def __str__(self):
        return '(%s, %s) ip: %s' % (self.X, self.Y, self.IP)

    def __repr__(self):
        return self.__str__()

考虑更好地格式化代码。使用
和缩进是三重压井。只需将所有内容缩进四个空格,您就可以得到代码格式。请将代码缩减到一个最小但仍能工作的示例,该示例仍然显示了问题所在。看,我修正了格式。关于减少代码,我只是尝试传递对象坐标。我想不出另一个代码行数更少的类似情况。