1

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.

asked Dec 29, 2013 at 22:20
1
  • 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. Commented Dec 29, 2013 at 22:39

1 Answer 1

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

answered Dec 29, 2013 at 23:04
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.