I have simple code that asks multiple inputs from user and sends it to the server but the server only recieves the first message. How can I make the server get rest of the messages?
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
while True:
c,addr = s.accept()
sentence = c.recv(1024)
print(sentence.decode())
c.close()
I think the problem is in the server.py line 7. It awaits to accept connection therefore does not wait to receive data.
For server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
c,addr = s.accept()
while True:
sentence = c.recv(1024)
if sentence:
print(sentence.decode())
c.close()
For the client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()
Related
I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word.
When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don't.
I need to produce an endless cycle, where all inputs are sent to the server on print.
The server part:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
while True:
try:
client, addr = s.accept()
except KeyboardInterrupt:
s.close()
break
else:
res = client.recv(1024)
print(addr, 'says:', res.decode('utf-8'))
And the client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
while True:
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
if com == 'exit':
s.close()
break
I tried to do this on the client:
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
s.close()
if com == 'exit':
break
But this way needs to create a socket, make connection and close socket every iteration.
Is there the way how to do what I described above with only one socket initialization?
The s.close() must be out of the while loop.
So can someone please tell me how to have an admin-client shutting down the Server (server.py) in a socket multiple clients architecture? I want admin-client to type "shutdown" in client side then server will be shutdown. and right after submit, the server will call a function that shows network load graph . a graph with the number of requests per time slot.
Server:
`
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='bye':
break
print ("from client", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
Client:
import socket
SERVER = "127.0.0.1"
PORT = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER, PORT))
client.sendall(bytes("This is from Client",'UTF-8'))
while True:
in_data = client.recv(1024)
print("From Server :" ,in_data.decode())
out_data = input()
client.sendall(bytes(out_data,'UTF-8'))
if out_data=='bye':
break
client.close()
`
I have tried
if message == "shutdown":
close()
exit(0)
but dont know how to apply it
I have a p2p simple chat app in python. A server code receives the IP and port of peers and sends each peer address to another:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 44444))
while True:
clients = []
while True:
data, address = sock.recvfrom(128)
clients.append(address)
sock.sendto(b'ready', address)
if len(clients) == 2:
break
c1 = clients.pop()
c2 = clients.pop()
try:
sock.sendto('{} {} {}'.format(c1[0], c1[1], c2[1]).encode(), c2)
sock.sendto('{} {} {}'.format(c2[0], c2[1], c1[1]).encode(), c1)
except Exception as e:
print(str(e))
In my client code, first I start sending client info to the server (This part works properly):
import socket
import threading
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.bind(('', 40270))
sock.sendto(b'0', ('X.X.X.X', 44444))
while True:
data = sock.recv(1024).decode()
if data.strip() == 'ready':
break
ip, myport, dport = sock.recv(1024).decode().split(' ')
myport = int(myport)
dport = int(dport)
print('\n ip: {} , myport: {} , dest: {}'.format(ip, myport, sport))
This part of the code starts listening to the server after sending the current client's info to the server and when the other client gets connected, it receives its IP and port.
After connecting two clients and exchanging their addresses, a p2p connection is established between them.
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.bind(('', myport))
sock.sendto(b'0', (ip, dport))
print('ready to exchange messages\n')
Then, I run a thread to start listening to the other client like this:
def listen():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', myport))
while True:
data = s.recv(1024)
print('\rpeer: {}\n> '.format(data.decode()), end='')
listener = threading.Thread(target=listen, daemon=True)
listener.start()
Also, another socket is responsible to send messages:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', myport))
while True:
msg = input('> ')
s.sendto(msg.encode(), (ip, dport))
After all, as I said before, the server exchange the IP and port of clients properly. But messages were not received by another client after sending.
I think the problem is about the wrong port choice while I do the exchange.
Regards.
It is completely functional on Linux. The problem just occurred on a windows machine.
I make client-sever app. It look like this:
client
import socket
host = '127.0.0.1'
port = 1338
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
st = input("Your message: ")
byt = st.encode()
s.send(byt)
server
import socket
host = ''
port = 1338
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
while True:
s.listen(5)
conn, addr = s.accept()
data = conn.recv(2000)
print(data.decode())
Problem is that only first message is display. How can I solve this problem?
The server receives data only once after accepting a connection from the client. In-order to receive continuously, you can have a while loop for receiving data from the client.
import socket
host = ''
port = 1338
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
while True:
s.listen(5)
conn, addr = s.accept()
condition = True
while condition:
data = conn.recv(2000)
if not data: break
print(data.decode())
So, the above code will receive data as long the user provides data. You can separate the data receiving part in a separate thread too.
As you have the client's connect outside the loop, you have to place the server's listen and accept also outside the loop, since the connection is to be established only once.
A simple demo of socket programming in python:
server.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
print 'Received:', data
if not data:
break
conn.sendall(data)
print 'Sent:', data
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)
s.close()
Now code work well. However, the client may not know if server will always send back every time. I tried symmetric code of while-loop in server.py
client_2.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
data = s.recv(1024)
if not data:
break
print 'Received:', data
s.close()
This code will block at
data = s.recv(1024)
But in server.py, if no data received, it will be blank string, and break from while-loop
Why it does not work for client? How can I do for same functionality without using timeout?
You can set a socket to non-blocking operation via socket.setblocking(false), which is equivalent to socket.settimeout(0). Solving this "without using timeout" is impossible.