I have problem with python3 network (socket) programming. The problem is, when i run server.py everything is good. Than i open client.py, it must connect to server.py but it doesnt connect. It stays for 5-15 seconds then it gives error about connection. I give access python to use network. I dont know why its not working.
Server.py codes:
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 80
Buffer_Size = 1024
socket.bind((host, port))
socket.listen(1)
connectionNumber = 1
print("\n" + "[SERVER] Port" + str(port) + "opened. Connections are listening..." + "\n")
while True:
print("\n" + "*"*50)
print("[SERVER] Waitong connection {}...".format(connectionNumber))
conn, addr = socket.accept()
print("[SERVER] Connected to {}".format(addr))
print("[SERVER] Receiving bytes...")
while True:
msgFromClient = socket.recv(Buffer_Size)
if not msgFromClient:
print("[SERVER] No message received.")
break
print("[CLIENT]: {}".format(msgFromClient))
print("[SERVER] Message received, buffer emptied. " + connectionNumber + "Closing Connection...")
conn.send(str(msgFromClient) + ". You are the client. Thanks for connecting!")
conn.close()
print("[SERVER] Connection closed...")
connectionNumber += 1
client.py codes:
import getpass
pcName = getpass.getuser()
import socket
clientName = socket.gethostname()
clientIP = socket.gethostbyname(socket.gethostname())
sendingMessageToServer = pcName +"___" + clientName + "___"+ clientIP
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 80
Buffer_Size = 1024
clientSocket.connect((host, port))
print("Sending message: {}".format(sendingMessageToServer))
clientSocket.send(sendingMessageToServer)
print("Message Sended Succesfully!")
messageFromServer = clientSocket.recv(Buffer_Size)
print("[SERVER] Received message: {}".format(messageFromServer))
print("[CLIENT SERVER] Message received.. Closing connection...")
clientSocket.close()
First of all you should change your port 80 because it is used by http connection. Maybe your system is taking it over. Set for example port 8001. In server.py
you get incoming data from created conn
object, not socket
:
msgFromClient = conn.recv(Buffer_Size)
Also data received or sent through socket should be bytes
type, not str
therefore you should change all recv
and send
parameters to bytes, for example:
conn.send(msgFromClient + b". You are the client. Thanks for connecting!")
or in client.py
:
clientSocket.send(sendingMessageToServer.encode())
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.