Created
January 17, 2011 17:10
-
-
Save ecylmz/783105 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
require 'socket' | |
class ChatServer | |
def initialize(port) | |
@descriptors = [] | |
@serverSocket = TCPServer.new('',port) | |
@serverSocket.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR , 1 ) | |
puts "server started on port #{port}" | |
@descriptors << @serverSocket | |
end | |
def run | |
while 1 | |
res = select( @descriptors, nil, nil,nil) | |
if res != nil | |
res[0].each do |sock| | |
if sock == @serverSocket | |
accept_new_connection | |
name = `whoami` | |
@username = name.chop | |
else | |
if sock.eof? | |
str = sprintf("İstemci ayrıldı %s:%s\n", sock.peeraddr[2], sock.peeraddr[1]) | |
broadcast_string( str, sock ) | |
sock.close | |
@descriptors.delete(sock) | |
else | |
w = sock.gets | |
if w.chomp == "EOF" | |
str = sprintf("İstemci ayrıldı %s:%s\n", sock.peeraddr[2], sock.peeraddr[1]) | |
broadcast_string( str, sock ) | |
sock.close | |
@descriptors.delete(sock) | |
else | |
str = sprintf("[%s|%s]: %s", @username, sock.peeraddr[2], w) | |
broadcast_string(str,sock) | |
end | |
end | |
end | |
end | |
end | |
end | |
end | |
private | |
def broadcast_string ( str, omit_sock ) | |
@descriptors.each do |clisock| | |
if clisock != @serverSocket && clisock != omit_sock | |
clisock.write(str) | |
end | |
end | |
print(str) | |
end | |
def accept_new_connection | |
password = 12345 | |
newsock = @serverSocket.accept | |
@descriptors.push (newsock) | |
3.downto(1) do |count| | |
newsock.write("Parolayı Girin:") | |
reply = newsock.gets | |
if reply.chomp == "12345" | |
newsock.write("Çıkmak için EOF yazın...\n") | |
str = sprintf("İstemci Bağlandı %s:%s\n", | |
newsock.peeraddr[2], newsock.peeraddr[1]) | |
broadcast_string( str, newsock ) | |
break | |
else | |
newsock.write("Yanlış parola, #{count-1} hakkınız kaldı") | |
if count-1 == 0 | |
newsock.close | |
@descriptors.delete(newsock) | |
end | |
end | |
end | |
end | |
end | |
mc = ChatServer.new(2626) | |
mc.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
eline sağlık dostum güzel olmuş :P tüh tüh maşallah :P