Last active
          August 29, 2015 14:13 
        
      - 
      
 - 
        
Save asterite/69d1260c5045917ad8ab to your computer and use it in GitHub Desktop.  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | require "socket" | |
| class TCPServer | |
| def initialize(port, backlog = 128) | |
| @sock = C.socket(C::AF_INET, C::SOCK_STREAM, 0) | |
| optval = 1 | |
| C.setsockopt(@sock, C::SOL_SOCKET, 2, pointerof(optval) as Void*, sizeof(Int32)) | |
| addr = C::SockAddrIn.new | |
| addr.family = C::AF_INET | |
| addr.addr = 0_u32 | |
| addr.port = C.htons(port) | |
| if C.bind(@sock, pointerof(addr), 16) != 0 | |
| raise Errno.new("Error binding TCP server at #{port}") | |
| end | |
| if C.listen(@sock, backlog) != 0 | |
| raise Errno.new("Error listening TCP server at #{port}") | |
| end | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment