Created
May 10, 2012 10:34
-
-
Save ericchen/2652351 to your computer and use it in GitHub Desktop.
start a tcp client and server by eventmachine(two connection)
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
require 'rubygems' | |
require 'eventmachine' | |
require "socket" | |
module GwServer | |
# @server_socket = TCPSocket.open('127.0.0.1', 3000) | |
class GwTcpClient < EventMachine::Connection | |
def notify_readable | |
received_data = @io.read_nonblock(4096) | |
puts "INFO: notify_readable() => #{received_data.inspect}" | |
# Just for testing purposes: | |
sleep 1 | |
end | |
def post_init | |
puts "sending request to server" | |
send_data "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n" | |
end | |
def receive_data data | |
puts "recvs: #{data}" | |
end | |
end | |
class GwDataServer < EM::Connection | |
attr_accessor :server_socket | |
def post_init | |
puts "Acabei de me conectar" | |
# EM.start_server "127.0.0.0", 3000, TcpClient, self | |
end | |
def receive_data(data) | |
puts "recieve data:#{data}" | |
send_data ">>>you sent: #{data}" | |
end | |
def send_data_to_tcpserver data | |
@server_socket.puts "#{data}\n" | |
end | |
def get_message_from_tcp_server | |
end | |
end | |
def self.run | |
EM.run do | |
puts "dataServer running..." | |
EM.start_server("127.0.0.1", 8081, GwDataServer) do |s| | |
# s.server_socket = @server_socket | |
# conn = EventMachine.watch(@server_socket, TcpClient) | |
# conn.notify_readable = true | |
end | |
EventMachine::connect '127.0.0.1', 3000, GwTcpClient | |
end | |
end | |
end | |
GwServer.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment