Connecting 2 Pcs with sockets in python just wont work
here is the code for the server
import socket
host_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_socket.bind((socket.gethostbyname(socket.gethostname()), 9999))
host_socket.listen(5)
while True:
client, address = host_socket.accept()
print(f"Connection to {address} established")
print(client)
client.send(bytes("cheese", 'utf-8'))
and the code for the client
import socket
print(socket.gethostbyname(socket.gethostname()))
client_socket = socket.create_connection(('226.225.58.64', 9999))
print("Connected with the server on port 5000")
while True:
try:
message = client_socket.recv(4096)
except ConnectionResetError:
print("Connection closed by the server")
except TimeoutError:
pass
Additional information- We both are running python 3.9 on 2 PCs connected to wifi, assume random ip 226.225.58.64 is his ip, which is running server.py both are on the latest version of pycharm community and using its terminal
I think your issue is with receiving the message. The message is being sent correctly but you did not decode the message and did not print it as well.
while True:
try:
message = client_socket.recv(4096)
message = message.decode("utf-8")#since you sent it in utf-8 encoding, you have to decode it in utf-8 only
print(message)
use this code and check if it works for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.