I am trying to implement a very basic client and server chat in Python though having some trouble, the response I get is that I can only run the client or the server not both at the same time so I can't chat.
Client code:
#client
import socket
import time
HOST = "localhost"
PORT = 5454
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
data = raw_input("Enter..... ")
s.sendto(data,(Host,PORT))
print "Server says: " + s.recv(1024)
if data=="bye" or s.recv(1024)=="bye":
print "Exiting..........."
time.sleep(1)
break
Server code:
#server
import socket
import time
HOST = "localhost"
PORT = 5454
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print "Client says: " + s.recv(1024)
data = raw_input("Enter..... ")
s.sendto(data,(HOST, PORT))
if data=="bye" or s.recv(1024)=="bye":
print "Exiting.................."
time.sleep(1)
break
Also does the PORT automatically close after the program closes or do I need to manually close the PORT somehow.
-
On the client you side you don't want to bind, but connect. But that's not the only thing that's wrong here, have a look at the examples from the socket docs.ThinkChaos– ThinkChaos2013年12月29日 22:39:42 +00:00Commented Dec 29, 2013 at 22:39
1 Answer 1
On This page there is example code for sockets, which you can easily adapt to your program.
In your script the first problem was:
s.bind((HOST,PORT))#for client
because, server binds to ip, not client, which will connect to the server using obviously function:
s.connect((HOST,PORT))
The other problem was that, your wasn't listening for new connection, and accepting them:
s.listen(1) #number defines amount of queued connection to server
conn, addr = s.accept()
The last mistake was sending data to client without even being sure, if client connected to server.
Hope I helped you with the problem. KubaBest