到目前为止,我已经能够在 python 3.2中设计出一个基本的套接字。客户端向服务器发送一些数据,X 和 Y 坐标,服务器获取数据并返回确认消息。但我遇到的麻烦是让它在计算机之间收听。当我在同一台计算机上并排运行它们时,我的服务器和客户端运行良好,但我想让它们在不同计算机上运行时连接起来。
我楼上有一台电脑,楼下有一台电脑,都使用相同的无线互联网。有没有办法可以从这些计算机中的每一台连接我的服务器和客户端?
我已经尝试将服务器 IP 更改为我的无线调制解调器的 IP 地址,但这不起作用。
到目前为止,这是我的代码,唯一的区别是我将 IP 地址更改回标准环回地址,因为仅将其更改为我的 IP 不起作用:
客户:
import pygame, sys
from socket import socket, AF_INET, SOCK_DGRAM
from time import gmtime, strftime
from pygame.locals import *
SERVER_IP = '127.0.0.1'
PORT_NUMBER = 5000
SCREEN_X = 400
SCREEN_Y = 400
SIZE = 1024
PIC_PATH = "picture/path/goes/here.bmp"
print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))
mySocket = socket( AF_INET, SOCK_DGRAM )
x = y = 0
screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y)) #Make the screen
ending = False
word = "True"
clock = pygame.time.Clock() #tick-tock
grid = pygame.image.load(PIC_PATH) #Load the sheet
gridRect = grid.get_rect()
screen.blit(grid, gridRect)
pygame.display.flip()
while ending==False:
for event in pygame.event.get():
if event.type == KEYDOWN: # key down or up?
if event.key == K_RIGHT: x+=1
elif event.key == K_LEFT: x-=1
elif event.key == K_UP: y-=1
elif event.key == K_DOWN: y+=1
if event.key == K_ESCAPE:
ending=True # Time to leave
print("Stopped Early by user")
if ending==True: word="False"
localTime = strftime( "%H:%M:%S", gmtime() )
mySocket.sendto( bytes(str(x), 'UTF-8') , (SERVER_IP, PORT_NUMBER) )
mySocket.sendto( bytes(str(y), 'UTF-8') , (SERVER_IP, PORT_NUMBER) )
mySocket.sendto( bytes(word, 'UTF-8') , (SERVER_IP, PORT_NUMBER) )
print ("Sending packet... " + localTime)
clock.tick(10)
try:
(data, addr) = mySocket.recvfrom( SIZE )
print ("Received packet from: " + str(addr))
print ("Received: " + data.decode('UTF-8'))
except: ending=False
if ending==True:
pygame.quit()
sys.exit()
服务器:
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 5000
SIZE = 1024
hostName = gethostbyname( 'localhost' )
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
flag="True"
while flag=="True":
#Show that data was received:
(data, addr) = mySocket.recvfrom( SIZE )
xer=data.decode('UTF-8')
print ("Received packet from: " + str(addr) + ", X value:" + str(xer))
(data, addr) = mySocket.recvfrom( SIZE )
yer=data.decode('UTF-8')
print ("Received packet from: " + str(addr) + ", Y value:" + str(yer))
#Check to see if the other program wants to close:
(flagger, addr) = mySocket.recvfrom( SIZE )
flag=flagger.decode('UTF-8')
#Send a message back to the client:
if flag=="False": s="Good-bye!"
else: s="Read you loud and clear"
mySocket.sendto( bytes(s, 'UTF-8') , (addr) )
sys.exit()
万一你想知道为什么客户端这么大,那是因为我正在尝试用 pygame 制作一个多人游戏。不是互联网,而是我的两台计算机之间的 LAN 或无线网络。我对套接字和网络相关的东西非常陌生(我不知道 LAN 是否与无线基本相同或什么),因此非常感谢您对此的任何帮助。:)