问题描述
我正在尝试编写一个脚本,以使用套接字在Internet上传输图像(代码如下所示)。当我在本地计算机上尝试该代码时,代码工作正常,但是当我对连接到同一WiFi网络的2台不同计算机(1台用作服务器,1台作为客户端)进行相同操作时,它们甚至无法相互连接,独自传输数据。谁能帮忙吗?
服务器代码:-
import socket
import base64
import sys
import pickle
s = socket.socket(socket.AF_INET,socket.soCK_STREAM)
s.bind((socket.gethostname(),8487))
s.listen(5)
while True:
# After the Connection is established
(clientsocket,address) = s.accept()
print(f"Connection form {address} has been established!")
# Initiate image conversion into a string
with open("t.jpeg","rb") as imageFile:
string = base64.b64encode(imageFile.read())
msg = pickle.dumps(string)
print("Converted image to string")
# Send the converted string via socket encoding it in utf-8 format
clientsocket.send(msg)
clientsocket.close()
# Send a message that the string is sent
print("String sent")
sys.exit()
客户端代码:-
import socket,pickle,base64
s = socket.socket(socket.AF_INET,socket.soCK_STREAM)
s.connect((socket.gethostname(),8487))
while True:
data = []
# Recieve the message
while True:
packet = s.recv(1000000)
if not packet:
break
data.append(packet)
print("Message recieved")
# Decode the recieved message using pickle
print("Converting message to a String")
string = pickle.loads(b"".join(data))
print("Converted message to String")
# Convert the recieved message to image
imgdata = base64.b64decode(string)
filename = 'tu.jpeg'
with open(filename,'wb') as f:
f.write(imgdata)
s.shutdown()
s.close()
解决方法
s.connect((socket.gethostname(),8487))
您的客户端尝试连接到本地主机。如果服务器主机是本地主机,则可以使用。但是,如果服务器主机不同,则当然不会连接到服务器。相反,您必须在此处提供服务器系统的IP地址或主机名。