Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System.Collections.Generic
- Imports System.IO
- Imports System.Net.Sockets
- Imports System.Text
- Imports System.Text.RegularExpressions
- Imports System.Threading
- Namespace SethiCorporation
- NameSpace Irc
- Public Class ServerMessageEventArgs
- Inherits EventArgs
- Private m_Code As String
- Private m_Text As String
- Public Sub New(ByVal Code As String, ByVal MessageText As String)
- m_Code = Code
- m_Text = MessageText
- End Sub
- Public ReadOnly Property Code()As String
- Get
- Return m_Code
- End Get
- End Property
- Public ReadOnly Property MessageText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class NoticeEventArgs
- Inherits EventArgs
- Private m_Channel As String
- Private m_Text As String
- Public Sub New(ByVal Channel As String, ByVal NoticeText As String)
- m_Channel = Channel
- m_Text = NoticeText
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property NoticeText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class ChannelMessageEventArgs
- Inherits EventArgs
- Private m_Channel As String
- Private m_User As String
- Private m_Text As String
- Public Sub New(ByVal Channel As String, ByVal User As String, ByVal MessageText As String)
- m_Channel = Channel
- m_User = User
- m_Text = MessageText
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property MessageText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class PrivateMessageEventArgs
- Inherits EventArgs
- Private m_User As String
- Private m_Text As String
- Public Sub New(ByVal User As String, ByVal MessageText As String)
- m_User = User
- m_Text = MessageText
- End Sub
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property MessageText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class DisconnectedEventArgs
- Inherits EventArgs
- Private m_Text As String
- Public Sub New(ByVal ErrorText As String)
- m_Text = ErrorText
- End Sub
- Public ReadOnly Property ErrorText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class UserJoinedEventArgs
- Inherits EventArgs
- Private m_Channel As String
- Private m_User As String
- Public Sub New(ByVal Channel As String, ByVal UserName As String)
- m_Channel = Channel
- m_User = UserName
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- End Class
- Public Class NickChangedEventArgs
- Inherits EventArgs
- Private m_OldNick As String
- Private m_NewNick As String
- Public Sub New(ByVal OldNick As String, ByVal NewNick As String)
- m_OldNick = OldNick
- m_NewNick = NewNick
- End Sub
- Public ReadOnly Property OldNick()As String
- Get
- Return m_OldNick
- End Get
- End Property
- Public ReadOnly Property NewNick()As String
- Get
- Return m_NewNick
- End Get
- End Property
- End Class
- Public Class InviteEventArgs
- Inherits EventArgs
- Private m_User As String
- Private m_Channel As String
- Public Sub New(ByVal UserName As String, ByVal Channel As String)
- m_User = UserName
- m_Channel = Channel
- End Sub
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- End Class
- Public Class KickEventArgs
- Inherits EventArgs
- Private m_Mod As String
- Private m_Channel As String
- Private m_User As String
- Public Sub New(ByVal ModeratorName As String, ByVal Channel As String, ByVal UserName As String)
- m_Mod = ModeratorName
- m_Channel = Channel
- m_User = UserName
- End Sub
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property ModeratorName()As String
- Get
- Return m_Mod
- End Get
- End Property
- End Class
- Public Class ModeEventArgs
- Inherits EventArgs
- Private m_Mod As String
- Private m_Channel As String
- Private m_Mode As String
- Public Sub New(ByVal ModeratorName As String, ByVal Channel As String, ByVal Mode As String)
- m_Mod = ModeratorName
- m_Channel = Channel
- m_Mode = Mode
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property ModeratorName()As String
- Get
- Return m_Mod
- End Get
- End Property
- Public ReadOnly Property Mode()As String
- Get
- Return m_Mode
- End Get
- End Property
- End Class
- Public Class PartChannelEventArgs
- Inherits EventArgs
- Private m_Channel As String
- Private m_User As String
- Private m_Text As String
- Public Sub New(ByVal Channel As String, ByVal UserName As String, ByVal MessageText As String)
- m_Channel = Channel
- m_User = UserName
- m_Text = MessageText
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property MessageText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class QuitEventArgs
- Inherits EventArgs
- Private m_User As String
- Private m_Text As String
- Public Sub New(ByVal UserName As String, ByVal MessageText As String)
- m_User = UserName
- m_Text = MessageText
- End Sub
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property MessageText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class TopicEventArgs
- Inherits EventArgs
- Private m_Channel As String
- Private m_User As String
- Private m_Topic As String
- Public Sub New(ByVal Channel As String, ByVal UserName As String, ByVal TopicText As String)
- m_User = UserName
- m_Channel = Channel
- m_Topic = TopicText
- End Sub
- Public ReadOnly Property Channel()As String
- Get
- Return m_Channel
- End Get
- End Property
- Public ReadOnly Property UserName()As String
- Get
- Return m_User
- End Get
- End Property
- Public ReadOnly Property TopicText()As String
- Get
- Return m_Topic
- End Get
- End Property
- End Class
- Public Class RawMessageEventArgs
- Inherits EventArgs
- Private m_Raw As String
- Public Sub New(ByVal RawMessage As String)
- m_Raw = RawMessage
- End Sub
- Public ReadOnly Property RawMessage()As String
- Get
- Return m_Raw
- End Get
- End Property
- End Class
- Public Class PingEventArgs
- Inherits EventArgs
- Private m_Server As String
- Public Sub New(ByVal Server As String)
- m_Server = Server
- End Sub
- Public ReadOnly Property Server()As String
- Get
- Return m_Server
- End Get
- End Property
- End Class
- Public Class PongEventArgs
- Inherits EventArgs
- Private m_Server As String
- Public Sub New(ByVal Server As String)
- m_Server = Server
- End Sub
- Public ReadOnly Property Server()As String
- Get
- Return m_Server
- End Get
- End Property
- End Class
- Public Class ErrorEventArgs
- Inherits EventArgs
- Private m_Text As String
- Public Sub New(ByVal ErrorText As String)
- m_Text = ErrorText
- End Sub
- Public ReadOnly Property ErrorText()As String
- Get
- Return m_Text
- End Get
- End Property
- End Class
- Public Class IrcClient
- Private m_Stream As NetworkStream
- Private m_TcpIrcClient As TcpClient
- Private m_Password As String
- Private m_Nick As String
- Private m_Server As String
- Private m_Port As Integer
- Private m_UserName As String
- Private m_RealName As String
- Private m_Connected As Boolean
- Private m_Encoding As Text.Encoding
- Private m_Invisible As Boolean
- Private m_AutoPong As Boolean
- #Region "События"
- ''' <summary>
- ''' Сообщение сервера
- ''' </summary>
- Public Event ServerMessage(ByVal sender As Object, ByVal e As ServerMessageEventArgs)
- ''' <summary>
- ''' Уведомление
- ''' </summary>
- Public Event Notice(ByVal sender As Object, ByVal e As NoticeEventArgs)
- ''' <summary>
- ''' Сообщение с канала
- ''' </summary>
- Public Event ChannelMessage(ByVal sender As Object, ByVal e As ChannelMessageEventArgs)
- ''' <summary>
- ''' Личное сообщение
- ''' </summary>
- Public Event PrivateMessage(ByVal sender As Object, ByVal e As PrivateMessageEventArgs)
- ''' <summary>
- ''' Принято сырое сообщение
- ''' </summary>
- Public Event ReceivedRawMessage(ByVal sender As Object, ByVal e As RawMessageEventArgs)
- ''' <summary>
- ''' Отправлено сырое сообщение
- ''' </summary>
- Public Event SendedRawMessage(ByVal sender As Object, ByVal e As RawMessageEventArgs)
- ''' <summary>
- ''' Отключение от сервера
- ''' </summary>
- Public Event Disconnected(ByVal sender As Object, ByVal e As DisconnectedEventArgs)
- Public Event Ping(ByVal sender As Object, ByVal e As PingEventArgs)
- Public Event Pong(ByVal sender As Object, ByVal e As PongEventArgs)
- Public Event IrcError(ByVal sender As Object, ByVal e As ErrorEventArgs)
- ''' <summary>
- ''' Пользователь присоединился к каналу
- ''' </summary>
- ''' <remarks></remarks>
- Public Event UserJoined(ByVal sender As Object, ByVal e As UserJoinedEventArgs)
- ''' <summary>
- ''' Пользователь сменил ник
- ''' </summary>
- Public Event NickChanged(ByVal sender As Object, ByVal e As NickChangedEventArgs)
- ''' <summary>
- ''' Приглашение пользователя на канал
- ''' </summary>
- Public Event Invite(ByVal sender As Object, ByVal e As InviteEventArgs)
- ''' <summary>
- ''' Удар по пользователю
- ''' </summary>
- Public Event Kick(ByVal sender As Object, ByVal e As KickEventArgs)
- ''' <summary>
- ''' Смена режима
- ''' </summary>
- Public Event Mode(ByVal sender As Object, ByVal e As ModeEventArgs)
- ''' <summary>
- ''' Пользователь покидает канал
- ''' </summary>
- Public Event PartChannel(ByVal sender As Object, ByVal e As PartChannelEventArgs)
- ''' <summary>
- ''' Пользователь покидает сервер
- ''' </summary>
- Public Event Quit(ByVal sender As Object, ByVal e As QuitEventArgs)
- ''' <summary>
- ''' Смена темы
- ''' </summary>
- Public Event Topic(ByVal sender As Object, ByVal e As TopicEventArgs)
- #End Region
- #Region "Свойства"
- ''' <summary>
- ''' Возвращает или задёт значение, позволяющее автоматически отвечать на пинг сервера
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks>При отключении этого свойства отправку команд PONG необходимо производить самостоятельно, иначе сервер закроет соединение</remarks>
- Public Property AutoPong() As Boolean
- Get
- Return m_AutoPong
- End Get
- Set(ByVal Value As Boolean)
- m_AutoPong = Value
- End Set
- End Property
- ''' <summary>
- ''' Кодировка для передачи сообщений. По умолчанию используется UTF-8
- ''' </summary>
- ''' <value></value>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Property Encoding() As Text.Encoding
- Get
- Return m_Encoding
- End Get
- Set(ByVal value As Text.Encoding)
- m_Encoding = value
- End Set
- End Property
- ''' <summary>
- ''' Ник бота
- ''' </summary>
- Public Property Nick() As String
- Get
- Return m_nick
- End Get
- Set(ByVal Value As String)
- m_nick = Value
- If m_Connected Then
- SendData("NICK " & m_Nick)
- End If
- End Set
- End Property
- ''' <summary>
- ''' Пароль подключения
- ''' </summary>
- Public Property Password() As String
- Get
- Return m_Password
- End Get
- Set(ByVal Value As String)
- m_Password = Value
- End Set
- End Property
- ''' <summary>
- ''' Проверка подключения к серверу
- ''' </summary>
- Public ReadOnly Property Connected() As Boolean
- Get
- Return m_Connected
- End Get
- End Property
- ''' <summary>
- ''' Невидимый режим
- ''' </summary>
- Public Property IsInvisible As Boolean
- Get
- Return m_Invisible
- End Get
- Set(ByVal Value As Boolean)
- m_Invisible = Value
- End Set
- End Property
- #End Region
- Private Sub Initialize()
- m_AutoPong = True
- End Sub
- Public Sub New()
- Initialize()
- End Sub
- ''' <summary>
- ''' Инициализация экземпляра класса Irc и подключение к серверу
- ''' </summary>
- ''' <param name="strServer">Адрес Irc-сервера</param>
- ''' <param name="intPort">Порт Irc-сервера</param>
- ''' <param name="strNick">Ник Irc-пользователя</param>
- ''' <param name="strUserName">Имя пользователя</param>
- ''' <param name="strRealName">Реальное имя пользователя</param>
- ''' <param name="enc">Кодировка текста</param>
- Public Sub New(ByVal strServer As String, ByVal intPort As Integer, ByVal strNick As String, ByVal strUserName As String, ByVal strRealName As String, ByVal enc As Text.Encoding)
- Initialize()
- m_Encoding = enc
- m_Server = strServer
- m_Port = intPort
- m_Nick = strNick
- m_UserName = strUserName
- m_RealName = strRealName
- Me.Open()
- End Sub
- ''' <summary>
- ''' Инициализация экземпляра класса Irc с кодировкой utf8 и подключение к серверу
- ''' </summary>
- ''' <param name="strServer">Адрес Irc-сервера</param>
- ''' <param name="intPort">Порт Irc-сервера</param>
- ''' <param name="strNick">Ник Irc-пользователя</param>
- ''' <param name="strUserName">Имя пользователя</param>
- Public Sub New(ByVal strServer As String, ByVal intPort As Integer, ByVal strNick As String, ByVal strUserName As String)
- Initialize()
- m_Encoding = Encoding.UTF8
- m_Server = strServer
- m_Port = intPort
- m_Nick = strNick
- m_UserName = strUserName
- Me.Open()
- End Sub
- ''' <summary>
- ''' Открывает соединение с сервером
- ''' </summary>
- Public Function Open()As Boolean
- ' данные регистрации
- Dim sb As StringBuilder = New StringBuilder
- ' пароль
- If Not String.IsNullOrEmpty(m_Password) Then
- sb.AppendLine("PASS " & m_Password)
- End If
- ' ник
- sb.AppendLine("NICK " & m_Nick)
- ' Юзер-строка
- sb.AppendLine(String.Format("USER {0} {1} * :{2}", m_UserName, If(m_Invisible, "8", "0"), If(String.IsNullOrEmpty(m_RealName), m_Nick, m_RealName)))
- Dim bytes() As Byte = m_Encoding.GetBytes(sb.ToString())
- ' Новый интернет-клиент
- Try
- m_TcpIrcClient = New TcpClient(m_Server, m_Port)
- m_Stream = m_TcpIrcClient.GetStream()
- m_Stream.Write(bytes, 0, bytes.Length)
- ' Ставим флаг, что мы подключились к серверу
- m_Connected = True
- RaiseEvent SendedRawMessage(Me, New RawMessageEventArgs(sb.ToString()))
- Catch ex As Exception
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- End Try
- If m_Connected Then
- Dim st As New StateObject With {.NS = m_Stream, .sb = String.Empty}
- Redim st.buffer(1024 * 1024 - 1)
- m_Stream.BeginRead(st.buffer, 0, 1024 * 1024, AddressOf EndRead, st)
- End If
- Return m_Connected
- End Function
- Private Sub EndRead(ByVal ar As IAsyncResult)
- Dim st As StateObject = CType(ar.AsyncState, StateObject)
- Dim intBytesCount As Integer
- Try
- intBytesCount = st.NS.EndRead(ar)
- Catch ex As Exception
- ' закрыть соединение
- m_Connected = False
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- RaiseEvent Disconnected(Me, New DisconnectedEventArgs(ex.Message))
- End Try
- If m_Connected Then
- Dim st1 As New StateObject With {.NS = m_Stream}
- Redim st1.buffer(StateObject.BytesCount - 1)
- ' Теперь получить строку из байт
- Dim strRet As String = m_Encoding.GetString(st.buffer, 0, intBytesCount)
- ' Разбить строку построчно
- Dim strLines() As String = Regex.Split(strRet, "\r\n")'strRet.Split(vbCrLf)
- If st.sb.Length > 0 Then
- strLines(0) = st.sb & strLines(0)
- End If
- ' Проверить последний элемент в массиве
- If strLines(strLines.Length - 1).Length = 0 Then
- st1.sb = String.Empty
- Else
- st1.sb = strLines(strLines.Length - 1)
- End If
- ' Проходим массив строк за вычетом последнего элемента
- For i As Integer = 0 To strLines.Length - 2
- RaiseEvent ReceivedRawMessage(Me, New RawMessageEventArgs(strLines(i)))
- ParseData(strLines(i))
- Next
- Try
- m_Stream.BeginRead(st1.buffer, 0, StateObject.BytesCount, AddressOf EndRead, st1)
- Catch ex As Exception
- ' закрыть соединение
- m_Connected = False
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- RaiseEvent Disconnected(Me, New DisconnectedEventArgs(ex.Message))
- End Try
- End If
- End Sub
- ''' <summary>
- ''' Закрыть соединение
- ''' </summary>
- Public Sub [Close](ByVal strDisconnectText As String)
- If m_Connected Then
- Dim strMessage As String
- If String.IsNullOrEmpty(strDisconnectText) Then
- strMessage = "QUIT"
- Else
- strMessage = "QUIT :" & strDisconnectText
- End If
- SendData(strMessage)
- m_Connected = False
- RaiseEvent Disconnected(Me, New DisconnectedEventArgs(strDisconnectText))
- End If
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- End Sub
- #Region "Функции отправки команд на сервер"
- ''' <summary>
- ''' Отправить низкоуровневое сообщение серверу
- ''' </summary>
- ''' <param name="strMessage">Сообщение</param>
- Public Sub SendRawMessage(ByVal strMessage As String)
- REM For Each strLine As String In From s In Regex.Split(strMessage, "\r\n") Where s.Length > 0
- SendData(strMessage)
- REM Next
- End Sub
- ''' <summary>
- ''' Отправка NOTICE пользователю
- ''' </summary>
- ''' <param name="strNick">Ник пользователя, кому отправляется NOTICE</param>
- ''' <param name="strText">Текст сообщения для отправки</param>
- Public Sub SendNotice(ByVal strNick As String, ByVal strText As String)
- SendData(String.Format("NOTICE {0} :{1}", strNick, strText))
- End Sub
- ''' <summary>
- ''' Отправка сообщения в канал
- ''' </summary>
- ''' <param name="strChannel">Канал или имя пользователя</param>
- ''' <param name="strText">Текст сообщения</param>
- Public Sub SendMessage(ByVal strChannel As String, ByVal strText As String)
- SendData(String.Format("PRIVMSG {0} :{1}", strChannel, strText))
- End Sub
- ''' <summary>
- ''' Присоединение к каналу
- ''' </summary>
- ''' <param name="strChannel">Канал для присоединения</param>
- Public Sub JoinChannel(ByVal strChannel As String)
- SendData("JOIN " & strChannel)
- End Sub
- ''' <summary>
- ''' Отсоединение от канала
- ''' </summary>
- ''' <param name="strChannel">Канал для присоединения</param>
- ''' <param name="strExitText">Прощальный текст</param>
- Public Sub LeaveChannel(ByVal strChannel As String, strExitText As String)
- If String.IsNullOrEmpty(strExitText) Then
- SendData("PART " & strChannel)
- Else
- SendData(String.Format("PART {0} :{1}", strChannel, strExitText))
- End If
- End Sub
- #End Region
- ' Разбор данных от сервера
- Private Sub ParseData(ByVal data As String)
- Const Space As String = " "
- Dim ircData0 As String = data.Substring(0, data.IndexOf(Space))
- Select Case ircData0
- ' Если сообщение начинается с PING, мы должны отправить PONG
- Case "PING"
- Dim strServer As String = data.Substring(6)
- If m_AutoPong Then
- SendData("PONG " & strServer)
- End If
- RaiseEvent Ping(Me, New PingEventArgs(strServer))
- Case "PONG"
- ' Получен ответ от сервера
- RaiseEvent Pong(Me, New PongEventArgs(data.Substring(6)))
- Case "ERROR"
- RaiseEvent IrcError(Me, New ErrorEventArgs(data.Substring(6)))
- Case Else
- ' Разделить данные по пробелам
- Dim ircData() As String = data.Split()
- ' Определяем команду
- If ircData.Length > 1 Then
- ' Текст сообщения
- Dim lMessageText = Function() data.Substring(Math.Max(data.IndexOf(":", 2) + 1, 0))
- ' Имя пользователя
- Dim lUserName = Function() ircData0.Substring(1, Math.Max(ircData0.IndexOf("!") - 1, 0))
- Select Case ircData(1)
- Case "INVITE"
- If ircData.Length > 3 Then
- RaiseEvent Invite(Me, New InviteEventArgs(lUserName(), ircData(3)))
- End If
- Case "JOIN"
- If ircData.Length > 2 Then
- RaiseEvent UserJoined(Me, New UserJoinedEventArgs(ircData(2), lUserName()))
- End If
- Case "KICK"
- If ircData.Length > 3 Then
- RaiseEvent Kick(Me, New KickEventArgs(lUserName(), ircData(2), ircData(3)))
- End If
- Case "MODE"
- ' TODO Нужно что-то сделать с ircData(4)
- If ircData.Length > 3 Then
- RaiseEvent Mode(Me, New ModeEventArgs(lUserName(), ircData(2), ircData(3)))
- End If
- Case "NICK"
- RaiseEvent NickChanged(Me, New NickChangedEventArgs(lUserName(), ircData(2)))
- Case "NOTICE"
- If ircData.Length > 2 Then
- If ircData(2) = m_Nick Then
- RaiseEvent Notice(Me, New NoticeEventArgs(lUserName(), lMessageText()))
- Else
- RaiseEvent ServerMessage(Me, New ServerMessageEventArgs(lUserName(), lMessageText()))
- End If
- End If
- Case "PRIVMSG"
- If ircData.Length > 2 Then
- If ircData(2) = m_Nick Then
- RaiseEvent PrivateMessage(Me, New PrivateMessageEventArgs(lUserName(), lMessageText()))
- Else
- RaiseEvent ChannelMessage(Me, New ChannelMessageEventArgs(ircData(2), lUserName(), lMessageText()))
- End If
- End If
- Case "PART"
- If ircData.Length > 2 Then
- RaiseEvent PartChannel(Me, New PartChannelEventArgs(ircData(2), lUserName(), lMessageText()))
- End If
- Case "QUIT"
- RaiseEvent Quit(Me, New QuitEventArgs(lUserName(), lMessageText()))
- Case "TOPIC"
- If ircData.Length > 2 Then
- RaiseEvent Topic(Me, New TopicEventArgs(ircData(2), lUserName(), lMessageText()))
- End If
- Case Else
- RaiseEvent ServerMessage(Me, New ServerMessageEventArgs(ircData(1), data.Substring(data.IndexOf(Space))))
- End Select
- End If
- End Select
- End Sub
- ' Отправка данных на сервер
- Private Sub SendData(ByVal strMessage As String)
- If m_Connected Then
- Dim lNewStr = Function() New StringBuilder(strMessage).AppendLine.ToString()
- Dim st As New StateObject With {.buffer = m_Encoding.GetBytes(lNewStr()), _
- .NS = m_Stream, _
- .sb = strMessage}
- Try
- m_Stream.BeginWrite(st.buffer, 0, st.buffer.Length, AddressOf EndWrite, st)
- Catch ex As Exception
- ' закрыть соединение
- m_Connected = False
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- RaiseEvent Disconnected(Me, New DisconnectedEventArgs(ex.Message))
- End Try
- End If
- End Sub
- Private Sub EndWrite(ByVal ar As IAsyncResult)
- Dim st As StateObject = CType(ar.AsyncState, StateObject)
- Try
- st.NS.EndWrite(ar)
- Catch ex As Exception
- ' закрыть соединение
- m_Connected = False
- If m_Stream IsNot Nothing Then
- m_Stream.Close()
- End If
- If m_TcpIrcClient IsNot Nothing Then
- m_TcpIrcClient.Close()
- End If
- RaiseEvent Disconnected(Me, New DisconnectedEventArgs(ex.Message))
- End Try
- If m_Connected Then
- RaiseEvent SendedRawMessage(Me, New RawMessageEventArgs(st.sb))
- End If
- End Sub
- Private Class StateObject
- ' Сетевой поток
- Public NS As NetworkStream
- ' Буфер приёма данных
- Public buffer() As Byte
- ' Строка для отправки
- Public sb As String
- ' Размер буфера в один килобайт
- Public Const BytesCount As Integer = 512
- End Class
- End Class
- End Namespace
- End NameSpace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement