Python socket sends the first message but nothing afterward - python

My socket sends the first message but nothing afterward.
The output in the server:
What do you want to send?
lol
The client receives:
From localhost got message:
lol
And then it doesn't want to send anything else.
I don't get the what do you want to send printed anymore.
My code:
server.py file:
#!/usr/bin/python3
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
print ("got host name:", host)
port = 9996
print("connecting on port:", port)
# bind to the port
serversocket.bind((host, port))
print("binding host and port")
# queue up to 5 requests
serversocket.listen(5)
print("Waiting for connection")
while True:
clientsocket, addr = serversocket.accept()
msg = input("what do you want to send?\n")
clientsocket.send(msg.encode('ascii'))
client.py file:
#!/usr/bin/python3
import socket # create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine
# name
host = socket.gethostname()
port = 9996 # connection to hostname on the port.
s.connect((host, port)) # Receive no more than 1024 bytes
while True:
msg = s.recv(1024)
print(msg.decode("ascii"))

The client only connects once (OK) but the server waits for an incoming connection every start of the while loop.
Since there are no more connection requests by a client, the server will freeze on the second iteration.
If you just want to handle a single client, move clientsocket, addr = serversocket.accept() before the while loop. If you want to handle multiple clients, the standard way is to have the server accept connections inside the while loop and spawn a thread for each client.
You can also use coroutines, but that may be a bit overkill if you are just starting out.

Related

How to send continous data from server to client in Python?

I am building a server to send data to the client in Python. I would like to continuously send the time until the client closes the connection. So far, I have done :
For the server:
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
For the client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()
How can I modify the server to continously send the current date? At the moment, the server is just sending one date and closing the connection.
you need to use While True loop.
import socket
from datetime import datetime
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at server side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# bind the socket with server
# and port number
s.bind(('', port))
# allow maximum 1 connection to
# the socket
s.listen(1)
# wait till a client accept
# connection
while True:
c, addr = s.accept()
# display client address
print("CONNECTION FROM:", str(addr))
dateTimeObj = str(datetime.now())
print(dateTimeObj)
c.send(dateTimeObj.encode())
# disconnect the server
c.close()
client:
import socket
# take the server name and port name
host = 'local host'
port = 5001
# create a socket at client side
# using TCP / IP protocol
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
# connect it to server and port
# number on local computer.
s.connect(('127.0.0.1', port))
# receive message string from
# server, at a time 1024 B
while True:
msg = s.recv(1024)
# repeat as long as message
# string are not empty
while msg:
print('Received date :' + msg.decode())
msg = s.recv(1024)
# disconnect the client
s.close()

TCP connection with Python sockets - send() function issue

I am trying to establish TCP connection on the client-side using socket. The first part seem to work fine:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 1234 # The port used by the server
s.connect((HOST, PORT))
Now for the send() the server-side requires:
Once a client is connected it needs to send the following string in order to send a marker: <TRIGGER>XXXX</TRIGGER>In our case XXX is defined as var.trigger
When I write it like s.send(bytes (var.trigger)) it runs with no errors, however, I guess because it is not defined as a string the server does not recognize it.
Thank you in advance
p.s. I don't code in Python so it can be something very basic that I am missing here.
I am also fairly new to python sockets, but I tried this and it worked. My guess is that you need to wait for the data to be sent (on your server side) with something like this:
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
The full code is as follows:
import socket
# ========== SERVER ==========
def server():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) # Setting up socket
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept() # Accepting connection
print("========== SERVER ==========")
print("Connected by:", addr)
while True: # Infinite loop
data = conn.recv(1024) # 1024 = number of bytes to be recieves
if not data: # If data is false, or an empty string/list, etc.
break
print("Recieved:", data.decode('utf-8')) # Printing recieved data
# ========== CLIENT ==========
def client():
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
HOST = '127.0.0.1' # Localhost
PORT = 65432
s.connect((HOST, PORT)) # Connecting to server
print("========== CLIENT ==========")
var = 'XXXX' # Replace with actual variable
s.sendall(f"<TRIGGER>{var}<TRIGGER>".encode('utf-8')) # Sending trigger message
print(f"Sent: <TRIGGER>{var}<TRIGGER>")

Print is not showing result when executing this simple socket connection code in python. Why is the print not showing result?

I have the following client/server python code. The print line from the server where i used f-string interpolation does not show anything when the code is executed and I would like to know why?
I followed this tutorial and on their end the print line shows result.
tutorial: https://www.tutorialspoint.com/python/python_networking.htm
line: Got connection from ('127.0.0.1', 48437)
my server code:
#!/usr/bin/python
# Server.py
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Get local machine name
host = socket.gethostname()
# Reserve a port number for the socket service
port = 22226
# Bind the host address and the port number
s.bind((host, port))
# Listens for the client connections made for the socket.
# The argument shows maximum number of queued connections and it is 1 at minimum
s.listen(5)
while True:
# Establish connection with client.
c, addr = s.accept()
print(f"Got connection from {addr}")
c.send(b'Thank you for connecting')
c.close() # Close the connection
my client code:
#!/usr/bin/python
# client.py
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Get local machine name
host = socket.gethostname()
# Reserve a port number for the socket service
port = 22226
# Connect the host address and the port number
s.connect((host, port))
# Read at most 1024 bytes
print(s.recv(1024))
s.close() # Close the socket when done

Is there a way to send two messages with socket

Im trying to send a messages from the server to the client
I tried deleting the .close and puting a while loop on print but it still doesn't won't to work
Client
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
while True:
print (s.recv(1024))
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print ('Got connection from', addr)
x = str(input("ënter a message"))
data = x.encode()
c.send(data)
I expect the output to be 2 messages from the server but it is only sending 1 and then closing the connection
Switch your accept and while True: lines. Once you accept a connection, keep sending on the same connection.
Note that TCP is a streaming protocol. There is no concept of "messages", but just a bunch of bytes. If you send fast enough, such as:
c.send(b'abc')
c.send(b'def')
then recv(1024) could receive b'abcdef'. For more complex communication, you'll have to define a protocol and buffer recv until you are sure you have a complete message. A simple way in this case is read until you find a newline, or send a byte (or more) indicating the size of the total message before sending the actual message.

Python UDP Socket File Transfer

How do I get a response from the server?
Client side:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
data_c = input()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port))
print( data_c )
print( c.recv(1024).decode('utf-8'))
SERVER side:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print(s.recv(1024).decode('utf-8'))
I can send a message from the server that the client will receive, but can not seem to get communication (like an ACK.) to make it back to the server.
(yes UDP is not a good way to be doing this i'm pretty sure, but that was a specific for the project)
for question 1: to send the ACK, you could replicate what you have in the reverse direction.
Since UDP is connection-less you don't know beforehand you receive a packet where the packet will come from, so you have to use recvfrom to get both the packet and the peer (address/port) the packet came from. Then you have to use that address to send data back.
What you're doing now in your client (but what really looks like the server) in the loop is send the same data over and over to itself. Instead in the loop you should receive packets using the previously mentions recvfrom then send replies to the peer you received the packet from.
So something like the following pseudo code
while True:
peer = recvfrom(...)
sendto(..., peer)
After many attempts to get a simple acknowledgment reply from my server this did it.
Beyond literally starting completely over each round, the time.sleep(.1) function was the only missing key. It allowed the server and client both time to close the current socket connection so that there was not an error of trying to bind multiple bodies to a single location or something.
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Working result:
#SERVER
import socket
import time
host = "localhost"
port = 5454
data_s = "ACKNOWLEDGMENT"
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
received = print("Client: " + s.recv(1024).decode('utf-8')) #waiting to receive
s.close
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
s.sendto(bytes(data_s, 'utf-8'),(host,port)) #sending acknowledgment
print("Server: " + data_s)
s.close # close out so that nothing sketchy happens
time.sleep(.1) # the delay keeps the binding from happening to quickly
Server Command Window:
>>>
Client: hello
Server: ACKNOWLEDGMENT
Client:
#CLIENT
import socket
import time
host = "localhost"
port = 5454
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while 1:
data_c = input("Client: ")
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.sendto(bytes(data_c, 'utf-8'),(host,port)) #send message
c.close
# time.sleep()
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.bind((host, port))
print("Server: " + c.recv(1024).decode('utf-8')) # waiting for acknowledgment
c.close
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
time.sleep(.1)
Client Command Window:
>>>
Client: hello
Client: hello
Server: ACKNOWLEDGMENT
I did finally remove the redundant input("Client: ") there at the top.
A special thanks #JoachimPileborg for helping, but I have to give it to the little guy just because it was the path I ended up taking.

Categories

Resources