Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only receiving one byte from socket

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,))   
like image 629
programmer Avatar asked Nov 05 '12 09:11

programmer


People also ask

How many bytes is a socket?

A socket address for the internet domain is made up of 4 distinct parts defined by 16 bytes: The first 2 bytes contain the domain parameter, which indicates the address space where communication is taking place.

What does recv() return?

If successful, recv() returns the length of the message or datagram in bytes. The value 0 indicates the connection is closed.

How do you transfer bytes to a socket?

The send() method can be used to send data from a TCP based client socket to a TCP based client-connected socket at the server side and vice versa. The data sent should be in bytes format. String data can be converted to bytes by using the encode() method of string class.

How does socket receive work?

The Receive method reads data into the buffer parameter and returns the number of bytes successfully read. You can call Receive from both connection-oriented and connectionless sockets. This overload only requires you to provide a receive buffer, the number of bytes you want to receive, and the necessary SocketFlags.


1 Answers

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:]
like image 102
Tim Avatar answered Oct 04 '22 00:10

Tim