Socket Server Example with Swift

前端 未结 2 1631
温柔的废话
温柔的废话 2020-12-10 14:22

I tried to make an example of simple socket server.

Build and run successfully. However it doesn\'t work well.

Client couldn\'t connect to this server.

相关标签:
2条回答
  • 2020-12-10 14:38

    The port number in the socket address must be in big-endian byte order:

    server_addr.sin_port = UInt16(4000).bigEndian
    

    So your program actually listens on port 40975 (hex 0xA00F) and not on port 4000 (hex 0x0FA0).

    Another problem is here:

    var buff_rcv: Array<CChar> = []
    // ...
    read(client_socket, &buff_rcv, UInt(BUFF_SIZE))
    

    Your buffer is an empty array, but recv() expects a buffer of size BUFF_SIZE. The behaviour is undefined. To get a buffer of the required size, use

    var buff_rcv = [CChar](count:BUFF_SIZE, repeatedValue:0)
    // ...
    read(client_socket, &buff_rcv, UInt(buff_rcv.count))
    

    Remark: Here you cast the address of an Int to the address of an socklen_t and pass that to the accept() function:

    client_socket = accept(server_socket, sockaddr_cast(&client_addr), socklen_t_cast(&client_addr_size))
    

    That is not safe. If Int and socklen_t have different sizes then the behaviour will be undefined. You should declare server_addr_size and client_addr_size as socklen_t and remove the socklen_t_cast() function:

    client_socket = accept(server_socket, sockaddr_cast(&client_addr), &client_addr_size)
    
    0 讨论(0)
  • 2020-12-10 14:45

    As Martin R commented before, the write command shouldn't be using the swift string as that. Something like this will work properly:

    write(client_socket, buff_snd.cStringUsingEncoding(NSUTF8StringEncoding)!, countElements(buff_snd) + 1)
    
    0 讨论(0)
提交回复
热议问题