Send/Receive Python chat room not working (updated) - python

I asked a question about my server to client code because I had many problems with and someone told me that the solution to the problems I had was to make a peer to peer chat which I have now done.
Server.py
import socket, threading
host = "127.0.0.1"
port = 4000
s = socket.socket()
s.bind((host,port))
s.listen(5)
client_sockets = []
users = []
print("Listening")
def handle_client(conn):
while True:
try:
data = conn.recv(512)
for x in client_sockets:
try:
x.send(data)
except Exception as e:
print(e)
except:
pass
while True:
conn,addr = s.accept()
client_sockets.append(conn)
print("Connections from", addr[0], "on port",addr[1])
threading.Thread(target = handle_client,args = (conn,)).start()
Client.py
import socket,threading
host = "127.0.0.1"
port = 4000
s = socket.socket()
s.connect((host,port))
def echo_data(sock):
while True:
try:
data = sock.recv(512)
print(data)
except:
pass
while True:
threading.Thread(target=echo_data,args=(s,)).start()
msg = input("Enter your message : ")
s.send(msg.encode())
The problems is that when I run the client and try talking to another client the message doesn't get sent unless the other client hits enter and also that brings me to my second problem, when the clients send messages to each other they get received in this format:
b'hi'Enter your message :
This is the link to my previous question

I will start with general problems not directly related to the question:
except: pass is generally a bad idea, specially when things go wrong because it will hide potentially useful messages. It is allowed by the language but should never exist in real code
in client.py you start a receiving thread per message, while you only need one for the whole client. You should start the thread outside the loop:
threading.Thread(target=echo_data,args=(s,)).start()
while True:
msg = input("Enter your message : ")
s.send(msg.encode())
Now for the questions:
the message doesn't get sent unless the other client hits enter
It can be caused by an IDE. Specifically, IDLE is known to behave poorly with multi-threaded scripts. If you correctly use one single receiving thread and starts the script from the command line (python client.py) it should work correctly
the messages get recived in this format: b'hi'Enter your message
sock.recv(sz) returns a byte string. You need to decode it to convert it to a Python 3 unicode string:
data = sock.recv(512)
print(data.decode())
But that is not all. It is fine for tests, but you should at least allow clients to disconnect from the server and when they do, remove them from client_sockets. And it is common not to send back a message to the sender. So you could improve the server.py loop:
while True:
try:
data = conn.recv(512)
for x in client_sockets:
if x != conn: # do not echo to sender
x.send(data)
except Exception as e: # problem in connection: exit the loop
print(e)
break
# clear the connection
conn.close()
client_sockets.remove(conn)

Related

How do I make my socket keep trying to connect even after the connection is closed?

So I am writing this program that will allow me to run commands from a different computer on the same network (my own version of ssh) in Python. I want the client program to run in the background of the target which I've already figured out the logistics to. What I would like to do is start the client program and never have to start it again but after I close the server program on the host computer, I get tons of errors. What I would like to do is after I close the host program, the client will continue to try to connect to the server program until I run it again. The code for my client program is here:
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect():
try:
s.connect(('localhost', 1234))
except:
connect()
while True:
connect()
while True:
try:
msg = s.recv(1024)
os.system(msg.decode("utf-8"))
except:
s.connect('localhost', 1234)
The code for my host program is here:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1234))
s.listen(5)
def main():
while True:
clientsocket, address = s.accept()
while address != None:
message = input("Enter Message: ")
messageb = message.encode("utf-8")
clientsocket.send(messageb)
main()
Note: I will change the address from localhost when I put this on a different computer.
Never do the following to start over a function without understanding the consequences of recursion. A function calling itself is called recursion and uses stack space. This will crash if the stack hits the recursion limit.
def connect():
try:
s.connect(('localhost', 1234))
except:
connect()
Here's a solution.
client.py:
import socket
import time
while True:
s = socket.socket()
try:
print('Trying to connect...')
s.connect(('localhost',8000))
print('Connected.')
try:
while True:
data = s.recv(1024)
if not data: break # server closed connection if nothing received.
print(data)
finally:
s.close()
print('Disconnected.')
except ConnectionError: # Any type of connection error, e.g. refused, aborted, reset.
time.sleep(1)
server.py:
import socket
import time
s = socket.socket()
s.bind(('',8000))
s.listen()
while True:
c,a = s.accept()
print(f'Connected: {a}')
try:
while True:
c.send(b'message')
time.sleep(1)
except ConnectionError:
c.close()
print(f'Disconnected: {a}')
Note also that TCP is a streaming protocol. It has no concept of messages. Take the time.sleep(1) out and the messages will all run together. A proper implementation will have a protocol to extract complete messages from the byte stream such as fixed sized messages, size transmitted followed by message, delimiter bytes like newlines between messages, etc.

Terminating client connection to server using keyboard shortcut in python

I am trying to modify a server and client chat script implemented in python. One of the requirement is that the client exits when the user types CTRL-D. My question is how do I read that the user typed (ctrl-D) and implement it within this code. Should I just close the socket like c_socket.close() without any message back to the server that I am exiting?
Thanks!
# telnet program example
import socket, select, string, sys
import readline
def prompt() :
sys.stdout.write('<You> ')
sys.stdout.flush()
#main function
if __name__ == "__main__":
if(len(sys.argv) < 3) :
print 'Usage : python MClient hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host. Start sending messages'
prompt()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
prompt()
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)
prompt()
Last thing first - whether you need to send something to the server before closing the socket or not depends purely on your protocol. Given the simplistic nature of the presented client code, I'd guess that closing of the socket should be enough (and the server should treat unannounced disconnects anyway as one shouldn't consider network I/O as persistent).
Second, CTRL+D will cause the returned message from sys.stdin.readline() to return as empty so you can test against that, e.g.:
msg = sys.stdin.readline()
if msg:
s.send(msg)
prompt()
else:
s.close()
sys.exit()
If you really need to send something to the server (again, depends on the protocol) you can use socket's shutdown() method before calling close().
However, keep in mind that the code presented here doesn't account for pressing the CTRL+D while reading from the socket (i.e. receiving data) so if there is a particularly long data stream coming in your CTRL+D won't be registered. You can solve this by checking the user input (and writing it to buffer for later sending) during the retrieval procedure, or you can just place your receiving code in a separate thread and leave the main thread just for user input.
You can then use the atexit module to cleanly exit from your client at any time.

Calling .recv(1024) and .send() twice, nothing happening (Python)

I am trying to learn Socket coding right now, and I wrote a little piece of Process-to-Process communication.
This is the Servercode:
import socket
s = socket.socket()
host = socket.gethostname()
port = 17752
s.bind((host, port))
s.listen(5)
while True:
(client, address) = s.accept()
print(address, 'just connected!')
message = input("Would you like to close the connection? (y/n)")
if message == 'y':
message = "False"
client.send(message.encode(encoding="utf_8"))
client.close()
break
elif message == 'n':
print("sending message...")
testing = "Do you want to close the connection?"
client.send(testing.encode(encoding='utf_8'))
print("sent!")
And the Clientcode:
import socket
client = socket.socket()
host = socket.gethostname()
port = 17752
client.connect((host, port))
while True:
print("awaiting closing message...")
closing = client.recv(1024)
closing = closing.decode(encoding='utf_8')
print("Closing message recieved and decoded")
if closing == 'False':
print("message is false, breaking loop")
break
else:
print("Awaiting message...")
recieved = client.recv(1024)
recieved = recieved.decode(encoding='utf_8')
print("Message recieved and decoded")
print(recieved)
sd = input('(y/n) >')
if sd == 'y':
print("Closing connection")
client.close()
break
print("Sorry, the server closed the connection!")
What it is meant to do?
It is basically to learn and practice socket coding.
It should be a program that sends data from the Server to the Client with both being able to terminate the connection by answering y or n to the questions.
If both sides keep answering n the program just keeps running.
As soon as someone answers y it terminates either the Server or the client.
Now, I don't know what to heck is wrong there.
If I type 'y' for the Servers question "Would you like to close this connection?" it all works as it should.
If I type 'n' the Server does what it should, but the client does not recieve anything. Most of the 'print' statements are for debugging. Thats how I know the Server works fine.
What is wrong there? I tried to find it, I couldn't.
I am kinda new to python and new to socket coding. So keep it easy please.
Thanks.
(I run it with Batch scripts under Win10 cmd)
(Since it is Process-to-Process it is probably not called a "Server"?)
In you code each connect should have a matching accept on server side.
Your client connects once per session,
but the server accepts after each message, so at the point where the second recv is invoked the server is already trying to accept another client.
Apparently your server is supposed to handle only one client,
so you can just move the call to accept out of the loop:
s.listen(5)
(client, address) = s.accept()
print(address, 'just connected!')
while True:
message = raw_input("Would you like to close the connection? (y/n)")

python3 - broken pipe error when using socket.send()

I am programming a client-server instant message program. I created a similar program in Python 2, and am trying to program it in Python 3. The problem is when the server takes the message and tries to send it to the other client, it gives me "[Errno 32] Broken Pipe" and exits.
I have done some research, and found that this occurs when the client disconnects, so I did some more testing but could not find when the client disconnects. (I am using Ubuntu 14.04 and Python 3.4)
Here is the server code:
import socket, select, sys
def broadcast(sock, messaged):
for socket in connection_list:
if socket != s and socket != sock:
# Here is where it gives me the broken pipe error
try:
s.send(messaged.encode("utf-8"))
except BrokenPipeError as e:
print(e)
sys.exit()
connection_list = []
host = ''
port = 5558
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(5)
connection_list.append(s)
read_sockets,write_sockets,error_sockets = select.select(connection_list,[],[])
while True:
for sock in read_sockets:
if sock == s:
conn, addr = s.accept()
connection_list.append(conn)
client = "Client (%s,%s) connected" % addr
print(client)
broadcast(sock,client)
else:
try:
data = sock.recv(2048)
decodeddata = data.decode("utf-8")
if data:
broadcast(sock, decodeddata)
except:
offline = "Client " + addr + "is offline"
broadcast(sock, offline)
print(offline)
connection_list.remove(sock)
sock.close()
continue
And the client code:
import socket, select, string, sys, time
def prompt(data) :
print("<You> " + data)
def Person(data) :
print("<Receiver> " + data)
if __name__ == "__main__":
host = "localhost"
port = 5558
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((host,port))
except:
print('Unable to connect')
sys.exit()
print('Connected.')
socket_list = [s]
read_sockets,write_sockets,error_sockets = select.select(socket_list,[],[])
while 1:
for sock in read_sockets:
if sock == s:
try:
time.sleep(1)
data = sock.recv(1024)
Person(data.decode("utf-8"))
except:
msg = input("Send a message: ")
try:
s.send(str.encode(msg))
except:
print("Server is offline")
sys.exit()
else:
print("Server is offline")
sys.exit()
There are two problems that you have to fix to make this work.
First, on both the client side and the server side, you have to put the select inside the loop, not outside. Otherwise, if there was something to read before you got to the loop, you'll recv over and over, and if there wasn't, you'll never recv. Once you fix this, you can get rid of the time.sleep(1). (You should never need a sleep to solve a problem like this; at best it masks the problem, and usually introduces new ones.)
Meanwhile, on the server side, inside broadcast, you're doing s.send. But s is your listener socket, not a connected client socket. You want socket.send here, because socket is each socket in connection_list.
There are a number of unrelated problems in your code as well. For example:
I'm not sure what the except: in the client is supposed to be catching. What it mainly seems to catch is that, about 50% of the time, hitting ^C to end the program triggers the send prompt. But of course, like any bare except:, it also masks any other problems with your code.
There's no way to send any data back and forth other than the "connected" message except for that except: clause.
addr is a tuple of host and port, so when someone goes offline, the server raises a TypeError from trying to format the offline message.
addr is always the last client who connected, not the one who's disconnecting.
You're not setting your sockets to nonblocking mode.
You're not checking for EOF on the recv. This means that you don't actually detect that a client has gone offline until you get an error. Which normally happens only after you try to send them a message (e.g., because someone else has connected or disconnected).

s.sendall doesn't work inside a thread in python

I'm trying to develop a chat program in python. I want it to have multiple clients so I'm using threading to handle this. However when I try to send the message to all connected clients, the server only sends it to the client which sent the message. I'm not sure if I'm just missing something obvious but here is the code for the server:
import socket
from thread import *
host = '192.168.0.13'
port = 1024
users = int(input("enter number of users: "))
def clienthandler(conn):
while True:
data = conn.recv(1024)
if not data:
break
print data
conn.sendall(data)
conn.close()
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind((host, port))
serversock.listen(users)
for i in range(users):
conn, addr= serversock.accept()
print 'Connected by', addr
start_new_thread(clienthandler, (conn,))
And here is the code for the client:
import socket
host = '192.168.0.13'
port = 1024
usrname = raw_input("enter a username: ")
usrname = usrname + ": "
clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsock.connect((host, port))
while True:
x = raw_input('You: ')
x = usrname + x
clientsock.sendall(x)
data = clientsock.recv(1024)
print data
The "all" in sendall means that it sends all of the data you asked it to send. It doesn't mean it sends it on more than one connection. Such an interface would be totally impractical. For example, what would happen if another thread was in the middle of sending something else on one of the connections? What would happen if one of the connections had a full queue?
sendall: Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. -- 17.2. socket
You can try by pulling up the list of users, and iterating through it, and doing an individual send of the same message, though, unless you are the administrator and want to broadcast a warning, this functionality would be pretty mundane.

Categories