Simple Python 3 Chat; Sending and receiving at the same time - python

I am a total beginner in Python and today I tried to create a simple chat-program. So far it doesn't work too bad, but I am unable to communicate between the server and the client. I can only send from the server to the client but not in the other direction. I tried it with multithreading and these are the results:
Server:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.bind((host, port))
s.listen(3)
conn, addr = s.accept()
print("Connection from: "+str(addr[0])+":"+str(addr[1]))
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(socket.gethostname())+"> ")
msg = str(host + "> ").encode('utf-8') + msg.encode('utf-8')
conn.send(msg)
#t1 = threading.Thread(target=recv_data)
t2 = threading.Thread(target=send_data)
#t1.start()
t2.start()
Client:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.connect((host, port))
print("Connected to: "+ host)
def recv_data():
while True:
data = s.recv(2048)
data = data.decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(host)+"> ").encode('utf-8')
s.send(msg)
t1 = threading.Thread(target=recv_data)
#t2 = threading.Thread(target=send_data)
t1.start()
#t2.start()
This code works; the server can send, the client receive, but whenever I uncomment the second thread, so that it can do both I get an error:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
I can't seem to find a solution, so please help, what am I doing wrong? :D

conn, addr = s.accept()
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
conn is actually the socket you want to send or recv. The error occurs because you are trying to recv from the server socket, which is illegal action. Therefore you need to change s to conn if you want to make it work.

Related

Connection between client and server fails, send/recv doesnt work (python)

I have put together a server and client code to use in a messaging app. When I run the server and starts one client, everything works fine. When I start a second client, I can send messages from the first client and the second client will recieve them. I can send one message from the second client and the first client will recieve this first message. But after this message, the second client can not send or the server can not receive the data for some reason. The first client can still send messages.
I dont know where the mistake is, but I believe either the client can not .send() or the server can not .recv().
(I am quite new to programming so the code might be quite messy and not the most understandeble, and maybe there are several flaws...)
The server code
import socket
from _thread import *
import sys
HOST = "127.0.0.1"
PORT = 12000
client_socket = set()
def threaded(conn):
while True:
try:
data = conn.recv(1024).decode()
if not data:
print("Lost connection")
break
for conn in client_socket :
conn.send(data.encode())
except:
break
print("Gone")
conn.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print("Server is up and running")
while True:
conn, addr = s.accept()
print("Connected to", addr)
client_socket .add(conn)
start_new_thread(threaded, (conn, ))
The client code
import threading
import socket, sys
HOST = "127.0.0.1"
PORT = 12000
check= ""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def background():
while True:
answer= s.recv(1024).decode()
if check!= answer and answer!= "":
print(answer)
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()
while True:
message= input()
if message!= "":
s.send(message.encode())
check = message

Show all the clients connected to a socket server and send them data

I have this simple code:
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((host, port))
socket.listen()
while True:
client_socket, addr = socket.accept()
send = input("Send: ") # but I need a way to send it to all the clients connected
if send == "devices":
# here I'd have a list of all devices connected
client_socket.send(send.encode())
data = client_socket.recv(4096)
print (data)
As I wrote in the comments, I need a way to manage them all in one. How can I do? Maybe with _thread library?
You could mainitain a list of clients that can be passed to an external function that performs an action on all clients.
import socket
host = ''
port = 1000
max_connections = 5
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((host, port))
socket.listen(max_connections)
clients = [] # Maintain a list of clients
try:
while True:
client_socket, addr = socket.accept()
clients.append(client_socket) #Add client to list on connection
i_manage_clients(clients) #Call external function whenever necessary
except KeyboardInterrupt:
socket.close()
def i_manage_clients(clients): #Function to manage clients
for client in clients:
client.send('Message to pass')
The above example demonstrates how send data to all clients at once. You could use the
import socket
from thread import *
host = ''
port = 1000
max_connections = 5
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((host, port))
socket.listen(max_connections)
try:
while True:
client_socket, addr = socket.accept()
start_new_thread(i_manage_client, (client_socket,addr))
except KeyboardInterrupt:
socket.close()
def i_manage_client(client_socket, addr): #Function to manage clients
client_socket.send('Message to pass')
data = client_socket.recv(4096)
print(client_socket)
print(addr)
print(data)

TCP client server not receiving any data from each other

I have written the following TCP client and server using python socket module. However, after I run them, no output is being given. It seems that
the program is not able to come out of the while loop in the recv_all method
Server:
import socket
def recv_all(sock):
data = []
while True:
dat = sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '127.0.0.1'
PORT = 45678
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)
print "listening at", sock.getsockname()
while True:
s, addr = sock.accept()
print "receiving from", addr
final = recv_all(s)
print "the client sent", final
s.sendall("hello client")
s.close()
Client :
import socket
def recv_all(sock):
data=[]
while True:
dat=sock.recv(18)
if not dat:
break
data.append(dat)
return "".join(data)
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
PORT=45678
HOST='127.0.0.1'
sock.connect((HOST,PORT))
sock.sendall("hi server")
final=recv_all(sock)
print "the server sent",final
Because in server file you use an endless loop in another. I suggest you to edit recv_all method in both files this way:
def recv_all(sock):
data = []
dat = sock.recv(18)
data.append(dat)
return "".join(data)
But after edit like this your server stays on until KeyInterrupt, while you should run client file everytime you want to send data. If you want an automatically send/receive between server and client, I offer you try threading.

Error: Transport endpoint is not connected (Python Sockets)

I'm trying to create a simple chat application using sockets in Python (with threads). Application is simple client has to threads one to send data and another to receive. Server has to two threads one to accept client connection and another to broadcast the message. But on running the below code, I'm getting error message
Transport endpoint is not connected
Can anybody tell me why I'm getting this error
Client
import socket, threading
def send():
msg = raw_input('Me > ')
cli_sock.send(msg)
def receive():
data = cli_sock.recv(4096)
print('> '+ str(data))
if __name__ == "__main__":
# socket
cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect
HOST = 'localhost'
PORT = 5028
cli_sock.connect((HOST, PORT))
print('Connected to remote host...')
thread_send = threading.Thread(target = send)
thread_send.start()
thread_receive = threading.Thread(target = receive)
thread_receive.start()
Server
import socket, threading
def accept_client():
while True:
#accept
cli_sock, cli_add = ser_sock.accept()
CONNECTION_LIST.append(cli_sock)
print('Client (%s, %s) connected' % cli_add)
def broadcast_data():
while True:
data = ser_sock.recv(4096)
for csock in CONNECTION_LIST:
try:
csock.send(data)
except Exception as x:
print(x.message)
cli_sock.close()
CONNECTION_LIST.remove(cli_sock)
if __name__ == "__main__":
CONNECTION_LIST = []
# socket
ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind
HOST = 'localhost'
PORT = 5028
ser_sock.bind((HOST, PORT))
# listen
ser_sock.listen(1)
print('Chat server started on port : ' + str(PORT))
thread_ac = threading.Thread(target = accept_client)
thread_ac.start()
thread_bd = threading.Thread(target = broadcast_data)
thread_bd.start()
You're using server sockets incorrectly. You cannot recv on server sockets, instead you accept connections on them; accept returns the actual connection socket:
ser_sock.listen(1)
sock, addr = ser_sock.accept()
print('Got connection from {}'.format(addr))
# only this *connection* socket can receive!
data = sock.recv(4096)

Python server programming

I am trying a little client server project to get me into network programming but I seem to have got stuck at the first hurdle. I cant seem to get past getting the first line of data only even if its a new connection.
#!/usr/bin/python
import socket
s = socket.socket()
host = '192.168.0.233' # Test Server
port = 7777
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
data = c.recv(2048)
print(data)
If I telnet to the host running the server, the connection opens fine and I see on the server Got connection from addr, but I also only see the first line of data when I sent 4 lines of data,
I thought because its in a loop it should now always be looking for data?
I know im doing something wrong but unsure what.
Im using Python 2.6.6
recv needs to be in a loop too, at the moment your code is receiving some data and then waiting for a new connection.
https://docs.python.org/2/library/socket.html#example has an example of socket.recv in a loop.
Try this:
#!/usr/bin/python
import socket
import threading
def listenForClients(sock):
while True:
client, address = sock.accept()
client.settimeout(5)
threading.Thread( target = listenToClient, args = (client,address) ).start()
def listenToClient(client, address):
size = 2048
while True:
try:
data = client.recv(size)
if data:
response = "Got connection"
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
def main(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
listenForClients(sock)
if __name__ == "__main__":
main('192.168.0.233',7777)
Here I use a thread for each client. The problem that you have with having Socket.accept() in the loop is that it blocks meaning that concurrent access won't work and you'll only be able to talk to one client at a time.
Try running it in the background and sending it messages with:
#!/usr/bin/python
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.0.233',7777))
vwhile True:
data = raw_input("enter a message: ")
sock.send(data)
print sock.recv(2048)

Categories