我是套接字的新手。基本上我有一个套接字服务器。客户端本身就是一个移动的方块,它将coords发送到服务器。当我将2个客户端连接到服务器时,我将它们保存为自动生成的端口,并根据收到的数据将coords发送给其他客户端(在它们之间交换电源线),这样我就可以在以后制作多人游戏。
问题在于打印线
打印“%s - >%s”%(deserialized_obj.IP,sendTo)
它显示映射是正确的。但是当我移动方块并打印接收的数据时,它会写入自己的坐标,而另一个客户端的控制台则不受影响。
你怎么看?用这种方法创建它是否可以实现?这是套接字服务器:
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__()