Created
September 19, 2010 16:53
-
-
Save ruanwz/586925 to your computer and use it in GitHub Desktop.
This file contains 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
```ruby | |
require 'socket' | |
# Create the server using the Socket class | |
# AF_INET: using IP protocol | |
# SOCK_STREAM: using TCP | |
server_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) | |
# Set the socket address | |
sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) | |
# Bind the socket address to the server socket | |
server_socket.bind( sockaddr ) | |
# set the state to listen | |
server_socket.listen(5) | |
# Block for incoming connection from client by accept method | |
# The return value of accept contains the new client socket object and the remote socket address | |
client, client_sockaddr = server_socket.accept | |
# Receive data using recvfrom method on the new client socket | |
data = client.recvfrom( 20 )[0].chomp | |
puts "I only received 20 bytes '#{data}'" | |
# Send back the data | |
client.puts "You said: #{data}" | |
# Wait 1 second and close the server socket | |
sleep 1 | |
server_socket.close | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment