I'm trying to set up a small server where when the client logs in gets some messages.
The server code
import socket
#Networking
s = socket.socket()
print("Network successfully created")
port = 3642
s.bind(('',port))
print("Network has been binded to %s" %(port))
s.listen(5)
print("Waiting for connections")
while True:
c, addr = s.accept()
print("Got a connection from",addr)
c.send(bytes("Thank you for connecting to me. Currently we","utf-8"))
c.send(bytes("Working on the server","utf-8"))
c.close()
This is the client code
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 3642
# connect to the server on local computer
s.connect(('MyIp..', port))
# receive data from the server
print(s.recv(1024))
# close the connection
s.close()
Everything works fine such as the connecting and the first message gets printed, however I can't get the second message to get printed. The one that says working on the server. I have just began learning about sockets and barely know anything about them so the solution probably is obvious it's just I can't seem to figure it out. Thank you for any responses. (I would appreciate thorough responses)
1 Answer 1
If the two sent buffers happen to not get consolidated into a single buffer in the recv (which can happen based on timing, which OS you're running and other factors), then it makes sense that you would not see the second buffer because you're only making one recv call. If you want to receive everything the server sent, put the recv in a loop until it returns an empty string. (Empty string indicates end-of-file [i.e. socket closed by the other end].) – Gil Hamilton
sendwill (or at least may) get consolidated into a singlerecvbuffer (that's what I'm seeing). Other notes: (a) This is not valid python-3.x (on client-side, due to missing parentheses in the print statement); (b) You should put thec.close()inside the loop on the server side -- otherwise you're leaving all previously-accepted connections open until the program exits.recv(which can happen based on timing, which OS you're running and other factors), then it makes sense that you would not see the second buffer because you're only making onerecvcall. If you want to receive everything the server sent, put therecvin a loop until it returns an empty string. (Empty string indicates end-of-file [i.e. socket closed by the other end].)