Reputation: 75
I coded a server program using python.
I'm trying to get a string but i got only a character! How can I receive a string?
def handleclient(connection):
while True:
rec = connection.recv(200)
if rec == "help": #when I put help in the client program, rec = 'h' and not to "help"
connection.send("Help Menu!")
connection.send(rec)
connection.close()
def main():
while True:
connection, addr = sckobj.accept()
connection.send("Hello\n\r")
connection.send("Message: ")
IpClient = addr[0]
print 'Server was connected by :',IpClient
thread.start_new(handleclient, (connection,))
Upvotes: 6
Views: 6780
Reputation: 1
My solve for stupid embarcadero C++ Builder
char RecvBuffer[4096];
boolean first_init_flag = true;
while(true)
{
int bytesReceived;
while(true)
{
ZeroMemory(RecvBuffer, 4096);
bytesReceived = recv(clientSocket,(char*) &RecvBuffer, sizeof(RecvBuffer), 0);
std::cout << "RecvBuffer: " << RecvBuffer << std::endl;
std::cout << "bytesReceived: " << bytesReceived <<std ::endl;
if (!std::strcmp(RecvBuffer, "\r\n"))
{
if (first_init_flag) {
first_init_flag = !first_init_flag;
}
else
{
break;
}
}
}
if (bytesReceived == SOCKET_ERROR)
{
std::cout << "Client disconnected" << std::endl;
break;
}
send(clientSocket, RecvBuffer, bytesReceived + 1, 0);
}
Firstly, you send \r\n or ENTER for escape concatenating handshake and first data sending
Upvotes: 0
Reputation: 12174
With TCP/IP connections your message can be fragmented. It might send one letter at a time, or it might send the whole lot at once - you can never be sure.
Your programs needs to be able to handle this fragmentation. Either use a fixed length packet (so you always read X bytes) or send the length of the data at the start of each packet. If you are only sending ASCII letters, you can also use a specific character (eg \n
) to mark the end of transmission. In this case you would read until the message contains a \n
.
recv(200)
isn't guaranteed to receive 200 bytes - 200 is just the maximum.
This is an example of how your server could look:
rec = ""
while True:
rec += connection.recv(1024)
rec_end = rec.find('\n')
if rec_end != -1:
data = rec[:rec_end]
# Do whatever you want with data here
rec = rec[rec_end+1:]
Upvotes: 6