Страница: 1 |
|
Вопрос: Winsock .NET
|
Добавлено: 11.04.08 08:47
|
|
Автор вопроса: unw1s3 | ICQ: 923266
|
Кто нибуть может обьяснить, как с ним правильно работать?!
Работал с Винсоком в вб6, но там всё, естественно,по другому.
Или же, кто дружит с английским(не транслейт.ру и подобное =)) прошу перевести http://www.codeproject.com/KB/vb/winsockdotnet.aspx#intro
скачивал демо проект, тоже особо не понял в нём.
Ответить
|
Номер ответа: 4 Автор ответа: Artyom
Разработчик
Вопросов: 130 Ответов: 6602
|
Профиль | | #4
|
Добавлено: 03.04.11 22:25
|
Набросал примре асинхронного сервера/клиента. Корректно работает с многобайтовыми кодирвоками (в данном случае используется UTF-8)
Нет обработки ошибок, возомжности переподключения, возомжности подключения нескольких клиентов.
Писал под последнюю версию VB, на старых могут потребоваться доработки.
Сервер:
- Imports System.IO
- Imports System.Net
- Imports System.Net.Sockets
- Imports System.Text
-
- Module Module1
-
- Sub Main()
- Dim server As New ChatServer(50, Sub(m) Console.WriteLine("Received: {0}", m))
- server.StartListen()
- Do
- server.Send(Console.ReadLine())
- Loop
- End Sub
-
- End Module
-
- Public Class ChatServer
-
- Private _port As Int32
-
- Private _listener As TcpListener
- Private _client As TcpClient
- Private _clientStream As Stream
- Private _stringReadBuffer As New StringBuilder
- Private _readBuffer As Byte() = New Byte(8 * 1024 - 1) {}
- Private _decoder As System.Text.Decoder = System.Text.Encoding.UTF8.GetDecoder()
-
- Private _receivedCallback As Action(Of String)
-
- Public Sub New(port As Integer, receivedCallback As Action(Of String))
- _port = port
- _receivedCallback = receivedCallback
- End Sub
-
- Public Sub StartListen()
- _listener = New TcpListener(IPAddress.Any, _port)
- _listener.Start()
- _listener.BeginAcceptTcpClient(AddressOf ClientAcceptedCallback, Nothing)
- End Sub
-
- Private Sub ClientAcceptedCallback(ar As IAsyncResult)
- _client = _listener.EndAcceptTcpClient(ar)
- _clientStream = _client.GetStream
-
- _clientStream.BeginRead(_readBuffer, 0, _readBuffer.Length, AddressOf ClientReadCallback, Nothing)
- End Sub
-
- Private Sub ClientReadCallback(ar As IAsyncResult)
- Dim packetLength As Int32 = _clientStream.EndRead(ar)
-
- FillStringBuffer(packetLength)
-
- WriteReceivedMessages()
-
- _clientStream.BeginRead(_readBuffer, 0, _readBuffer.Length, AddressOf ClientReadCallback, Nothing)
- End Sub
-
- Private Sub FillStringBuffer(packetLength As Integer)
- Dim charsCount = _decoder.GetCharCount(_readBuffer, 0, packetLength)
-
- Dim chars(charsCount - 1) As Char
- _decoder.GetChars(_readBuffer, 0, packetLength, chars, 0)
-
- _stringReadBuffer.Append(chars)
- End Sub
-
- Private Sub WriteReceivedMessages()
- Dim messages As String() = _stringReadBuffer.ToString().Split(New String() {ControlChars.CrLf}, StringSplitOptions.None)
- For i As Integer = 0 To messages.Length - 2
- _receivedCallback(messages(i))
- Next
-
- _stringReadBuffer.Clear()
- _stringReadBuffer.Append(messages(messages.Length - 1))
- End Sub
-
- Public Sub Send(message As String)
- Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(message + ControlChars.CrLf)
- _clientStream.BeginWrite(buffer, 0, buffer.Length, AddressOf ClientWriteCallback, Nothing)
- End Sub
-
- Private Sub ClientWriteCallback(ar As IAsyncResult)
- _clientStream.EndWrite(ar)
- End Sub
- End Class
Клиент:
- Imports System.IO
- Imports System.Net.Sockets
- Imports System.Text
-
-
- Module Module1
- Sub Main()
- System.Threading.Thread.Sleep(500)
-
- Dim client As New ChatClient("127.0.0.1", 50, Sub(m) Console.WriteLine("Received: {0}", m))
- client.Connect()
- Do
- client.Send(Console.ReadLine())
- Loop
- End Sub
- End Module
-
- Public Class ChatClient
-
- Private _port As Int32
- Private _address As String
-
- Private _client As TcpClient
- Private _clientStream As Stream
- Private _stringReadBuffer As New StringBuilder
- Private _readBuffer As Byte() = New Byte(8 * 1024 - 1) {}
- Private _decoder As System.Text.Decoder = System.Text.Encoding.UTF8.GetDecoder()
-
- Private _receivedCallback As Action(Of String)
-
- Public Sub New(address As String, port As Integer, receivedCallback As Action(Of String))
- _port = port
- _address = address
- _receivedCallback = receivedCallback
- End Sub
-
- Public Sub Connect()
- _client = New TcpClient()
- _client.BeginConnect(_address, _port, AddressOf ClientConnectedCallback, Nothing)
- End Sub
-
- Private Sub ClientConnectedCallback(ar As IAsyncResult)
- _client.EndConnect(ar)
- _clientStream = _client.GetStream
-
- _clientStream.BeginRead(_readBuffer, 0, _readBuffer.Length, AddressOf ClientReadCallback, Nothing)
- End Sub
-
- Private Sub ClientReadCallback(ar As IAsyncResult)
- Dim packetLength As Int32 = _clientStream.EndRead(ar)
-
- FillStringBuffer(packetLength)
-
- WriteReceivedMessages()
-
- _clientStream.BeginRead(_readBuffer, 0, _readBuffer.Length, AddressOf ClientReadCallback, Nothing)
- End Sub
-
- Private Sub FillStringBuffer(packetLength As Integer)
- Dim charsCount = _decoder.GetCharCount(_readBuffer, 0, packetLength)
-
- Dim chars(charsCount - 1) As Char
- _decoder.GetChars(_readBuffer, 0, packetLength, chars, 0)
-
- _stringReadBuffer.Append(chars)
- End Sub
-
- Private Sub WriteReceivedMessages()
- Dim messages As String() = _stringReadBuffer.ToString().Split(New String() {ControlChars.CrLf}, StringSplitOptions.None)
- For i As Integer = 0 To messages.Length - 2
- _receivedCallback(messages(i))
- Next
-
- _stringReadBuffer.Clear()
- _stringReadBuffer.Append(messages(messages.Length - 1))
- End Sub
-
- Public Sub Send(message As String)
- Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(message + ControlChars.CrLf)
- _clientStream.BeginWrite(buffer, 0, buffer.Length, AddressOf ClientWriteCallback, Nothing)
- End Sub
-
- Private Sub ClientWriteCallback(ar As IAsyncResult)
- _clientStream.EndWrite(ar)
- End Sub
- End Class
Ответить
|
Страница: 1 |
Поиск по форуму