Python sockets objects - python

Consider the following example.
from socket import *
msg = input("Please enter your name ")
msg = msg.encode()
myHostIp = ''
myHostPort = 54040
socket_obj = socket(AF_INET, SOCK_STREAM)
socket_obj.bind((myHostIp,myHostPort))
socket_obj.listen(5)
while True:
connection,address = socket_obj.accept()
print("Client : ",address)
connection.send(msg)
print(socket.getsockname(socket_obj))
print(socket.getsockname(connection))
print(socket.getpeername(socket_obj))
print(socket.getpeername(connection))
while True:
data = connection.recv(1024)
print("This was received from ", data)
connection.close()
In this simple program the output of line print(socket.getsockname(socket_obj)) was (0.0.0.0)
and of the print(socket.getpeername(socket_obj)) was socket_obj is not connected.
My question is: once connection,address = socket_obj.accept() is executed, is the control from socket_obj transferred to connection?

The socket you call .listen() on is a server socket; about all you can do with it is to call .accept() to produce a client socket, which handles all actual communications. One server socket can produce any number of client sockets over its lifetime.

Related

I try to make chat room using Python and socket , but i have one problem

when I send message from client 1 , the message does not appear immediately in client 2 ,Although it appears immediately on the server, on client 2 i should double press "enter" to show other messages.
when I send message from client 1 , the message does not appear immediately in client 2 ,Although it appears immediately on the server, on client 2 i should double press "enter" to show other messages.
the server code :
import socket
import select
import sys
from _thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.bind((IP_address, Port))
server.listen(5)
list_of_clients = []
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message.encode())
except:
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send(b'chat made by galal')
while True:
try:
message = conn.recv(2048).decode()
if message:
print ("<" + addr[0] + "> " + message)
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
remove(conn)
except:
continue
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print (addr[0] + " connected")
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
the client code :
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
# maintains a list of possible input streams
sockets_list = [socket.socket(), server]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks != server:
message = sys.stdin.readline()
server.send(message.encode())
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
else:
message = socks.recv(2048).decode()
print (message)
server.close()
Your client code waits until pressed enter since there is a
sys.stdin.readline() in your client code (Line 17).
sys.stdin.readline() waits for the press of your enter key, since it tries to read a newline from your stdin (Your input), therefore blocking the whole execution of your client application.
What you have to do is using separate threads for:
Recieving messages + print them
Read from stdin (e.g. through sys.stdin.readline() or input()) and send that message to the server like you're already doing
I think the issue is the client's for loop.
sys.stdin.readline() stops the flow until Enter is pressed, so when you send a message from client1, client2 is still waiting for the user to write its own message. Basically since the first item in read_sockets is always socket.socket() every client's first action will be to wait for user input to send a message. The server on the other hand is always listening and never waits, so it receives it immediately.
To solve this you can either have an async connection, meaning you send 1 message then wait to receive 1 message and so on, or use multithreading and dedicate a thread to receiving and one to sending.

(Python) How can I receive messages in real-time without refreshing?

I have followed a tutorial from a YouTuber under the name of DrapsTV. This tutorial was made in Python 2.7 and makes a networked chat using UDP. I converted this to Python 3 and got everything to work. However, the way the threading is setup is that I have to send a message(or press enter, which is a blank message) to refresh and receive any messages from other clients. Here is the video incase you may need it: https://www.youtube.com/watch?v=PkfwX6RjRaI
And here is my server code:
from socket import *
import time
address = input("IP Address: ")
port = input("Port: ")
clients = []
serversock = socket(AF_INET, SOCK_DGRAM)
serversock.bind((address, int(port)))
serversock.setblocking(0)
quitting = False
print("Server is up and running so far.")
while not quitting:
try:
data, addr = serversock.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print(time.ctime(time.time()) + str(addr) + ": :" + str(data.decode()))
for client in clients:
serversock.sendto(data, client)
except:
pass
serversock.close()
Here is my client code:
from socket import *
import threading
import time
tLock = threading.Lock()
shutdown = False
def receiving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
print(str(data.decode()))
except:
pass
finally:
tLock.release()
address = input("IP Address: ")
port = 0
server = address, 6090
clientsock = socket(AF_INET, SOCK_DGRAM)
clientsock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
clientsock.bind((address, int(port)))
clientsock.setblocking(0)
rT = threading.Thread(target=receiving, args=("RecvThread", clientsock))
rT.start()
nick = input("How about we get you a nickname: ")
message = input(nick + "> ").encode()
while message != "q":
if message != "":
clientsock.sendto(nick.encode() + "> ".encode() + message, server)
tLock.acquire()
message = input(nick + "> ").encode()
tLock.release()
time.sleep(0.2)
shutdown = True
rT.join()
clientsock.close()
#furas has kindly explained my issue for me: it is not my receiving methods that are flawed(such as my threading or functions), it is the input call that is preventing the client from not receiving anything. So, in order to fix this, I or anyone else having this issue needs to find a way to call for input when a certain button is pressed so that unless your typing, you can receive messages or data.
Thank you #furas! https://stackoverflow.com/users/1832058/furas

How to connect a client to a server with sockets, using ip adress in Python?

This is probably very simple, but I am having trouble with it.
This is code I am using for the server.
I've searched for this but I only found different kinds of sockets to the one I am using.
server = socket.socket()
server.bind(("localhost", 6969))
server.listen(1)
socket_client, datos_client = server.accept()
print ("Wainting message...")
data = socket_client.recv(1000)
print ("Message:", data)
send1 = bytes("Bye","utf-8")
socket_client.send(send1)
print ("Closing..." )
socket_client.close()
server.close()
And this is the code for the client:
import socket
def main():
my_socket_client = socket.socket()
my_socket_client.connect(("localhost", 6969))
bufsize = 1000
print("Send message")
message=input()
data2 = bytes(mensaje,"utf-8")
#enviar los datos
my_socket_client.send(data2)
data_received= my_socket_client.recv(bufsize)
print (data_received)
I am not sure what your problem is since you didn't ask a question so i will just show you a client + basic command server that i have built in the same way you built yours you said "I only found different kinds of sockets to the one I am using." so i hope this is what you are looking for
Here is an example of a simple command server:
if you run the server code and then run the client you will be able to type in the client and send to the server. if you type TIME you will get from the server a respons which contains a string that has the date of today and the other commands work in the same way. if you type EXIT it will close the connection and will send from the server the string closing to the client
server:
import socket
import random
from datetime import date
server_socket = socket.socket() # new socket object
server_socket.bind(('0.0.0.0', 8820)) # empty bind (will connect to a real ip later)
server_socket.listen(1) # see if any client is trying to connect
(client_socket, client_address) = server_socket.accept() # accept the connection
while True: # main server loop
client_cmd = client_socket.recv(1024) # recive user input from client
# check waht command was entered
if client_cmd == "TIME":
client_socket.send(str(date.today())) # send the date
elif client_cmd == "NAME":
client_socket.send("best server ever") # send this text
elif client_cmd == "RAND":
client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
elif client_cmd == "EXIT":
client_socket.send("closing")
client_socket.close() # close the connection with the client
server_socket.close() # close the server
break
else :
client_socket.send("there was an error in the commend sent")
client_socket.close() # just in case try to close again
server_socket.close() # just in case try to close again
client:
import socket
client_socket = socket.socket() # new socket object
client_socket.connect(('127.0.0.1', 8820)) # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer
while True:
try:
print "please enter a commend"
print "TIME - request the current time"
print "NAME - request the name of the server"
print "RAND - request a random number"
print "EXIT - request to disconnect the sockets"
cmd = raw_input("please enter your name") # user input
client_socket.send(cmd) # send the string to the server
data = client_socket.recv(1024) # recive server output
print "the server sent: " + data # print that data from the server
print
if data == "closing":
break
except:
print "closing server"
break
client_socket.close() # close the connection with the server
you have a typo .
edit this line in client from
data2 = bytes(mensaje,"utf-8")
to
data2 = bytes(message,"utf-8")
I tried your code, and made a couple of changes:
Server side:
import socket
server = socket.socket()
server.bind(("localhost", 6969))
server.listen(1)
socket_client, datos_client = server.accept()
print ("Waiting message...")
data = socket_client.recv(1000)
print ("Message:", data )
# Same change made as with client side
send1 = bytes("Bye") #,"utf-8")
socket_client.send(send1)
print ("Closing..." )
socket_client.close()
server.close()
Client side:
import socket
my_socket_client = socket.socket()
my_socket_client.connect(("localhost", 6969))
bufsize = 1000
print("Send message")
# I changed it to raw_input(); input() does not for string input with python 2.7
message=raw_input()
# Are you trying to encode the message? To make it simple, skip it
data2 = bytes(message) # ,"utf-8")
#enviar los datos
my_socket_client.send(data2)
data_received= my_socket_client.recv(bufsize)
print (data_received)
Sample output from server side:
Waiting message...
('Message:', 'message from client')
Closing...
Sample output from client side:
Send message
message from client
Bye

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.

Choosing recepient of socket.send - Python socket module

I am trying to make a group chat program, where an unlimited amount of clients may join the server using the same script, it'll work by the server receiving the clients message and sending it to all the connected clients including the sender. I have only managed to make it so that the sender only gets his own message back, but not what another client sends.
I was thinking of storing all the connected client IP's in a list, and sending it to each IP, but I do not know how to change the recpient of socket.send
Server code:
from threading import *
import socket
s = socket.socket()
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)
print("Server host is", host)
def getMainThread():
for thread in enumerate():
if thread.name == 'MainThread':
return thread
return None
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.socket = socket
self.address = address
self.start()
def run(self):
main = getMainThread()
while main and main.isAlive():
print(self.address, "has connected!")
message = self.socket.recv(8192).decode('utf-8')
self.socket.send(bytes(message, 'UTF-8'))
self.socket.close()
while True:
c, addr = s.accept()
client(c, addr)
clients = [] #list for all client IP's
clients.append(addr)
Also, is there a way so that the client can establish a connection with the server so it doesn't keep poping up on the server.py that client has connected each time it sends a message?
Client code:
import socket
import os
import sys
host = '25.154.84.23'
print("""
=======================================================
=Welcome to Coder77's local internet messaging service=
=======================================================
The current soon to be encrypted server is {0}
You can enter the command /help for a list of commands available
""".format(host))
#username = input("Enter username: ")
username = 'Smile'
print("Now connecting to {0}....".format(host))
def printhelp():
print("""
The following commands are in the current version of this program:
/clear to clear the screen
/username to change your username
/exit to exit
/help for a list of commands
""")
def main():
global username
global host
sock = socket.socket()
try:
sock.connect((host, 1337))
while True:
message2 = input("{0}: ".format(username))
message = ('{0}: {1}'.format(username,message2))
if '/quit' in message:
sys.exit()
if '/clear' in message:
os.system('cls')
if '/help' in message:
printhelp()
if '/username' in message:
username = input("What would you like as your new username? ")
sock.send(bytes(message, 'UTF-8'))
received = sock.recv(8192).decode('utf-8')
print(received)
except socket.error:
print("Host is unreachable")
if __name__ == '__main__':
main()
#
Corrected Server code:
import sys
print(sys.version)
from threading import *
import socket
s = socket.socket()
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)
print("Server host is", host)
def getMainThread():
for thread in enumerate(): # Imported from threading
if thread.name == 'MainThread':
return thread
return None
class Client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.socket = socket
self.address = address
self.start()
def run(self):
main = getMainThread()
print(self.address, "has connected!")
while main and main.isAlive():
message = self.socket.recv(8192).decode('utf-8')
print(message)
self.socket.send(bytes(message, 'UTF-8'))
for each_client in clients:
each_client.socket.send(bytes(message, 'UTF-8'))
while True:
c, addr = s.accept()
this_client = Client(c, addr)
clients = []
clients.append(this_client)
The new code, adapted by gravetii is causing a lot of format errors. What happens now, is the user gets back what he sent, he does not get back what other users send and the user gets back what his previous message was, its terribly confusing. Please run the code, and you'll see as it's very hard to explain.
Example
In your server code, you are doing only a self.socket.send(bytes(message, 'UTF-8')). How can you then expect the server to send the message to all the clients? To do that you would need to iterate through the list of clients and call the send() method on each of their sockets.
while True:
c, addr = s.accept()
client(c, addr)
clients = [] #list for all client IP's
clients.append(addr)
In this code, you are creating a client object but never adding it to the list, then what's the point of creating one?
I think what you want is this:
while True:
c, addr = s.accept()
this_client = client(c, addr)
clients = [] #list for all client IP's
clients.append(this_client)
Then, you can send the message to all the clients by modifying the relevant part of your server code:
def run(self):
main = getMainThread()
while main and main.isAlive():
print(self.address, "has connected!")
message = self.socket.recv(8192).decode('utf-8')
self.socket.send(bytes(message, 'UTF-8'))
for each_client in clients:
each_client.socket.send(bytes(message, 'UTF-8'))
Also, why are you closing the connection after sending just one message? I believe your intention is to send more than one message to the server, and in that case, you don't need to close the connection.
Also, it's a better idea to create a class with its name starting with an upper case letter. So you may want to use Client instead of client for the class name.
Now coming to the issue of the message popping up everytime a client says something in your server.py, look at the run() method for the client thread:
def run(self):
main = getMainThread()
while main and main.isAlive():
print(self.address, "has connected!")
message = self.socket.recv(8192).decode('utf-8')
self.socket.send(bytes(message, 'UTF-8'))
The thread starts executing as soon as you create the client object, and so the first time when it connects to the server, it is right in showing that message. But then it's incorrect to place the print(self.address, "has connected!") in the while loop. So everytime the client says something, the server sends it back to the client and then the loop runs again, thus displaying the message back again. You need to modify it like so:
def run(self):
print(self.address, "has connected!")
main = getMainThread()
while main and main.isAlive():
message = self.socket.recv(8192).decode('utf-8')
self.socket.send(bytes(message, 'UTF-8'))
Hope this helps!

Categories