Visual Basic, .NET, ASP, VBScript
 

   
   
     

Форум - .NET

Страница: 1 | 2 | 3 | 4 | 5 | 6 |

 

  Вопрос: русские буквы Добавлено: 21.09.10 15:53  

Автор вопроса:  Ishayahu | Web-сайт: ishayahu.blogspot.com | ICQ: 329944992 
есть программа для работы через сеть . при посылке английского текста все работает замечательно, но при пересылке русского приходят одни лишь вопросы. как это можно исправить?

Ответить

  Ответы Всего ответов: 90  

Номер ответа: 1
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #1 Добавлено: 21.09.10 16:53
посылать правильно

Ответить

Номер ответа: 2
Автор ответа:
 UnDeAdZak



Вопросов: 80
Ответов: 476
 Профиль | | #2 Добавлено: 21.09.10 17:17
 Ishayahu в твоём случае скорее всего проблемы с кодировкой

Ответить

Номер ответа: 3
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #3
Добавлено: 21.09.10 20:13
и как это решается? даже не знаю, где смотреть...

Ответить

Номер ответа: 4
Автор ответа:
 AWP



ICQ: 345685652 

Вопросов: 96
Ответов: 1212
 Web-сайт: xawp.narod.ru
 Профиль | | #4
Добавлено: 21.09.10 20:42
Посылать в Юникоде.

Ответить

Номер ответа: 5
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #5
Добавлено: 22.09.10 07:37
AWPтак в том то и вопрос - как это сделать?

Ответить

Номер ответа: 6
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #6 Добавлено: 22.09.10 08:08
задать соответствующий параметр потоку

Ответить

Номер ответа: 7
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #7
Добавлено: 22.09.10 09:54
AgentFireа именно? можно чуть более подробно? я так и не смог нигде этого найти(

Ответить

Номер ответа: 8
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #8 Добавлено: 22.09.10 10:05
а можно чуть подробней в плане кода? откуда мне знать как ты работаешь с сетью, чтобы тебе правильно помочь..

Ответить

Номер ответа: 9
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #9
Добавлено: 22.09.10 10:49
загрузка формы
  1. Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2.         Dim pc As String = Environment.MachineName
  3.         pc.ToUpper()
  4.         If pc = "COMPY" Or pc = "COMPX" Or pc = "IT-COMP-Y" Then
  5.             txtDisplay.Enabled = True
  6.             txtSend.Enabled = True
  7.             btnSend.Enabled = True
  8.         Else
  9.             txtDisplay.Enabled = False
  10.             txtSend.Enabled = False
  11.             btnSend.Enabled = False
  12.         End If
  13.         txtDisplay.Text = Environment.MachineName
  14.         Dim frmConnectUser As New frmConnectUser()
  15.  
  16.         Try
  17.             ' The TcpClient is a subclass of Socket, providing higher level
  18.             ' functionality like streaming.
  19.             client = New TcpClient("1-509", PORT_NUM)
  20.  
  21.             ' Start an asynchronous read invoking DoRead to avoid lagging the user
  22.             ' interface.
  23.             client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
  24.  
  25.             ' Make sure the window is showing before popping up connection dialog.
  26.             Me.Show()
  27.  
  28.             AttemptLogin()
  29.         Catch Ex As Exception
  30.             MsgBox("Server is not active.  Please start server and try again.", _
  31.                    MsgBoxStyle.Exclamation, Me.Text)
  32.             Me.Dispose()
  33.         End Try
  34.  
  35.     End Sub



посылка данных
  1. Private Sub SendData(ByVal data As String)
  2.         Dim writer As New IO.StreamWriter(client.GetStream)
  3.         writer.Write(data & vbCr)
  4.         writer.Flush()
  5.     End Sub



прием данных

  1. Private Sub DoRead(ByVal ar As IAsyncResult)
  2.         Dim BytesRead As Integer
  3.         Dim strMessage As String
  4.  
  5.         Try
  6.             ' Finish asynchronous read into readBuffer and return number of bytes read.
  7.             BytesRead = client.GetStream.EndRead(ar)
  8.             If BytesRead < 1 Then
  9.                 ' If no bytes were read server has close.  Disable input window.
  10.                 MarkAsDisconnected()
  11.                 Exit Sub
  12.             End If
  13.  
  14.             ' Convert the byte array the message was saved into, minus two for the
  15.             ' Chr(13) and Chr(10)
  16.             strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 2)
  17.  
  18.             ProcessCommands(strMessage)
  19.  
  20.             ' Start a new asynchronous read into readBuffer.
  21.             client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
  22.         Catch e As Exception
  23.             MarkAsDisconnected()
  24.         End Try
  25.     End Sub

Ответить

Номер ответа: 10
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #10
Добавлено: 22.09.10 10:50
версия 2010 express

Ответить

Номер ответа: 11
Автор ответа:
 EROS



Вопросов: 58
Ответов: 4255
 Профиль | | #11 Добавлено: 22.09.10 11:02
Encoding.ASCII <=> Encoding.UTF8

Ответить

Номер ответа: 12
Автор ответа:
 Ishayahu



ICQ: 329944992 

Вопросов: 4
Ответов: 21
 Web-сайт: ishayahu.blogspot.com
 Профиль | | #12
Добавлено: 22.09.10 15:15
EROSспасибо
теперь осталась другая проблема - сообщения, которые приходят на сервер (выше был код клиента) все равно отображают вопросы, но там я ничего подобного кодировке не нашел. помогите еще раз!

  1.     Const PORT_NUM As Integer = 10000
  2.     Dim strprint As String
  3.  
  4.     Private clients As New Hashtable()
  5.     Private listener As TcpListener
  6.     Private listenerThread As Threading.Thread
  7.  
  8.     ' This subroutine sends a message to all attached clients
  9.     Private Sub Broadcast(ByVal strMessage As String)
  10.         Dim client As UserConnection
  11.         Dim entry As DictionaryEntry
  12.  
  13.         ' All entries in the clients Hashtable are UserConnection so it is possible
  14.         ' to assign it safely.
  15.         For Each entry In clients
  16.             client = CType(entry.Value, UserConnection)
  17.             client.SendData(strMessage)
  18.         Next
  19.     End Sub
  20.  
  21.     ' This subroutine sends the contents of the Broadcast textbox to all clients, if
  22.     ' it is not empty, and clears the textbox
  23.     Private Sub btnBroadcast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBroadcast.Click
  24.         If txtBroadcast.Text <> "" Then
  25.             UpdateStatus("Broadcasting: " & txtBroadcast.Text)
  26.             Broadcast("BROAD|" & txtBroadcast.Text)
  27.  
  28.             txtBroadcast.Text = ""
  29.         End If
  30.     End Sub
  31.  
  32.     ' This subroutine checks to see if username already exists in the clients
  33.     ' Hashtable.  If it does, send a REFUSE message, otherwise confirm with a JOIN.
  34.     Private Sub ConnectUser(ByVal userName As String, ByVal sender As UserConnection)
  35.         If clients.Contains(userName) Then
  36.             ReplyToSender("REFUSE", sender)
  37.         Else
  38.             sender.Name = userName
  39.             UpdateStatus(userName & " has joined the chat.")
  40.             clients.Add(userName, sender)
  41.  
  42.             ' Send a JOIN to sender, and notify all other clients that sender joined
  43.             ReplyToSender("JOIN", sender)
  44.             SendToClients("CHAT|" & sender.Name & " has joined the chat.", sender)
  45.         End If
  46.     End Sub
  47.  
  48.     ' This subroutine notifies other clients that sender left the chat, and removes
  49.     ' the name from the clients Hashtable
  50.     Private Sub DisconnectUser(ByVal sender As UserConnection)
  51.         UpdateStatus(sender.Name & " has left the chat.")
  52.         SendToClients("CHAT|" & sender.Name & " has left the chat.", sender)
  53.         clients.Remove(sender.Name)
  54.     End Sub
  55.  
  56.     ' This subroutine is used as a background listener thread to allow reading incoming
  57.     ' messages without lagging the user interface.
  58.     Private Sub DoListen()
  59.         Try
  60.             ' Listen for new connections.
  61.             listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
  62.             listener.Start()
  63.             Do
  64.                 ' Create a new user connection using TcpClient returned by
  65.                 ' TcpListener.AcceptTcpClient()
  66.                 Dim client As New UserConnection(listener.AcceptTcpClient)
  67.  
  68.                 ' Create an event handler to allow the UserConnection to communicate
  69.                 ' with the window.
  70.                 AddHandler client.LineReceived, AddressOf OnLineReceived
  71.                 UpdateStatus("New connection found: waiting for log-in")
  72.             Loop Until False
  73.         Catch
  74.         End Try
  75.     End Sub
  76.  
  77.     ' When the window closes, stop the listener.
  78.     Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
  79.         listener.Stop()
  80.     End Sub
  81.  
  82.     ' Start the background listener thread.
  83.     Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  84.         listenerThread = New Threading.Thread(AddressOf DoListen)
  85.         listenerThread.Start()
  86.         UpdateStatus("Listener started")
  87.         listtemp.Hide()
  88.         txtstatus.Hide()
  89.     End Sub
  90.  
  91.     ' Concatenate all the client names and send them to the user who requested user list
  92.     Private Sub ListUsers(ByVal sender As UserConnection)
  93.         Dim client As UserConnection
  94.         Dim entry As DictionaryEntry
  95.         Dim strUserList As String
  96.  
  97.         UpdateStatus("Sending " & sender.Name & " a list of users online.")
  98.  
  99.         strUserList = "LISTUSERS"
  100.  
  101.         ' All entries in the clients Hashtable are UserConnection so it is possible
  102.         ' to assign it safely.
  103.         For Each entry In clients
  104.             client = CType(entry.Value, UserConnection)
  105.             strUserList = strUserList & "|" & client.Name
  106.         Next
  107.  
  108.         ' Send the list to the sender.
  109.         ReplyToSender(strUserList, sender)
  110.     End Sub
  111.  
  112.     ' This is the event handler for the UserConnection when it receives a full line.
  113.     ' Parse the cammand and parameters and take appropriate action.
  114.     Private Sub OnLineReceived(ByVal sender As UserConnection, ByVal data As String)
  115.         Dim dataArray() As String
  116.  
  117.         ' Message parts are divided by "|"  Break the string into an array accordingly.
  118.         dataArray = data.Split(Chr(124))
  119.  
  120.         ' dataArray(0) is the command.
  121.         Select Case dataArray(0)
  122.             Case "CONNECT"
  123.                 ConnectUser(dataArray(1), sender)
  124.             Case "CHAT"
  125.                 SendChat(dataArray(1), sender)
  126.             Case "DISCONNECT"
  127.                 DisconnectUser(sender)
  128.             Case "REQUESTUSERS"
  129.                 ListUsers(sender)
  130.             Case "SRV"
  131.                 UpdateStatus("|" & dataArray(1))
  132.             Case Else
  133.                 UpdateStatus("Unknown message:" & data)
  134.         End Select
  135.     End Sub
  136.  
  137.     ' This subroutine sends a response to the sender.
  138.     Private Sub ReplyToSender(ByVal strMessage As String, ByVal sender As UserConnection)
  139.         sender.SendData(strMessage)
  140.     End Sub
  141.  
  142.     ' Send a chat message to all clients except sender.
  143.     Private Sub SendChat(ByVal message As String, ByVal sender As UserConnection)
  144.         UpdateStatus(sender.Name & ": " & message)
  145.         SendToClients("CHAT|" & sender.Name & ": " & message, sender)
  146.     End Sub
  147.  
  148.     ' This subroutine sends a message to all attached clients except the sender.
  149.     Private Sub SendToClients(ByVal strMessage As String, ByVal sender As UserConnection)
  150.         Dim client As UserConnection
  151.         Dim entry As DictionaryEntry
  152.  
  153.         ' All entries in the clients Hashtable are UserConnection so it is possible
  154.         ' to assign it safely.
  155.         For Each entry In clients
  156.             client = CType(entry.Value, UserConnection)
  157.  
  158.             ' Exclude the sender.
  159.             If client.Name <> sender.Name Then
  160.                 client.SendData(strMessage)
  161.             End If
  162.         Next
  163.     End Sub
  164.  
  165.  
  166.  
  167. End Class

Ответить

Номер ответа: 13
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #13 Добавлено: 22.09.10 15:53
юзай нормальные способы работы с сетью. у тебя как минимум с памятью проблемы будут огромные..

вот тебе мой личный класс да личное использование. не забывай ему вызывать Dispose в конце.
  1.  
  2. Public Class Winsock
  3.     Implements IDisposable
  4.  
  5.     Public Class Helper
  6.         Private WaitMs As UInt64
  7.         Private Procedure As Threading.ThreadStart
  8.  
  9.         ''' <summary>
  10.         ''' Waits specified time period in milliseconds with maximum of UInt64.MaxValue
  11.         ''' and then runs teh specified procedure
  12.         ''' </summary>
  13.         ''' <param name="Procedure">The procedure to run when the wait time is over</param>
  14.         ''' <param name="TimeMs">Time period to wait</param>
  15.         ''' <param name="Parameters">Currently useless</param>
  16.         Public Shared Sub RunIn(ByVal Procedure As Threading.ThreadStart, ByVal TimeMs As UInt64, Optional ByVal Parameters As Object = Nothing)
  17.             Dim I As New Helper
  18.             I.WaitMs = TimeMs
  19.             I.Procedure = Procedure
  20.             Dim BW = New BackgroundWorker
  21.             AddHandler BW.DoWork, AddressOf I.BW_Go
  22.             AddHandler BW.RunWorkerCompleted, AddressOf I.BW_Done
  23.             BW.RunWorkerAsync(Parameters)
  24.         End Sub
  25.         Private Sub BW_Go(ByVal sender As Object, ByVal e As DoWorkEventArgs)
  26.             e.Result = e.Argument
  27.             For i As UInt64 = 1 To WaitMs Step Int32.MaxValue
  28.                 Dim WaitInterval = If(WaitMs - i > Int32.MaxValue, Int32.MaxValue, Convert.ToInt32(WaitMs - i))
  29.                 Threading.Thread.Sleep(WaitInterval)
  30.             Next
  31.         End Sub
  32.         Private Sub BW_Done(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
  33.             Procedure.Invoke()
  34.             CType(sender, BackgroundWorker).Dispose()
  35.         End Sub
  36.     End Class
  37.  
  38.     Friend Const TimeoutIntervalMs As UInt64 = 30000
  39.  
  40.     Public Event OnDataReceive(ByVal Sender As Winsock, ByVal Data As Object)
  41.     Public Event OnConnect(ByVal Sender As Winsock)
  42.     Public Event OnClientAccept(ByVal Sender As Winsock)
  43.     Public Event OnConnectionLost(ByVal Sender As Winsock)
  44.     Public Event OnConnectFail(ByVal Sender As Winsock)
  45.  
  46.     Private TcpListener As Net.Sockets.TcpListener
  47.     Private TcpClient As Net.Sockets.TcpClient
  48.     Private WithEvents BWListener, BWReceiver, BWConnector As BackgroundWorker
  49.     Private nRemoteIP As Net.IPEndPoint
  50.     Private NS As Net.Sockets.NetworkStream, SW As IO.StreamWriter
  51.  
  52.     Private nLastAliveMsg As New Stopwatch
  53.  
  54.     Public ReadOnly Property LocalIPAddresses() As IEnumerable(Of Net.IPAddress)
  55.         Get
  56.             Return From ni In NetworkInterface.GetAllNetworkInterfaces() _
  57.                    Where ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback _
  58.                    From ipAddress In ni.GetIPProperties.UnicastAddresses _
  59.                    Select ipAddress.Address
  60.         End Get
  61.     End Property
  62.     Public ReadOnly Property RemoteIPAddress() As Net.IPAddress
  63.         Get
  64.             Return If(nRemoteIP Is Nothing, Nothing, nRemoteIP.Address)
  65.         End Get
  66.     End Property
  67.     Public ReadOnly Property Listening() As Boolean
  68.         Get
  69.             Return BWListener IsNot Nothing AndAlso BWListener.IsBusy
  70.         End Get
  71.     End Property
  72.     Public ReadOnly Property Connecting() As Boolean
  73.         Get
  74.             'we exist and we still not connected means we ARE connecting
  75.             Return TcpClient IsNot Nothing AndAlso Not TcpClient.Client.Connected
  76.         End Get
  77.     End Property
  78.     Public ReadOnly Property Connected() As Boolean
  79.         Get
  80.             Return TcpClient IsNot Nothing AndAlso TcpClient.Connected
  81.         End Get
  82.     End Property
  83.  
  84.     Public Function Connect(ByVal Address As String, ByVal Port As Int32) As Boolean
  85.         Try
  86.             StopEverything()
  87.             TcpClient = New Net.Sockets.TcpClient 'just to know if we are connecting here
  88.             BWConnector = New System.ComponentModel.BackgroundWorker
  89.             BWConnector.WorkerSupportsCancellation = True
  90.             BWConnector.RunWorkerAsync(New Object() {Address, Port})
  91.         Catch ex As Exception
  92.             Return False
  93.         End Try
  94.         Return True
  95.     End Function
  96.     Private Sub StopBW(ByRef BWs As IEnumerable(Of BackgroundWorker))
  97.         For Each iBW In BWs.Where(Function(T) T IsNot Nothing)
  98.             StopBW(iBW)
  99.         Next
  100.     End Sub
  101.     Private Sub StopBW(ByRef BW As BackgroundWorker)
  102.         BW.CancelAsync()
  103.         BW.Dispose()
  104.         BW = Nothing
  105.     End Sub
  106.     Public Sub StopEverything()
  107.         If SW IsNot Nothing Then
  108.             SW.Close()
  109.             SW.Dispose()
  110.         End If
  111.         If NS IsNot Nothing Then
  112.             NS.Close()
  113.             NS.Dispose()
  114.         End If
  115.  
  116.         StopBW(New BackgroundWorker() {BWReceiver, BWListener, BWConnector})
  117.  
  118.         If TcpListener IsNot Nothing Then
  119.             TcpListener.Stop()
  120.             TcpListener.Server.Close()
  121.             TcpListener = Nothing
  122.         End If
  123.         If TcpClient IsNot Nothing Then
  124.             TcpClient.Close()
  125.             TcpClient = Nothing
  126.         End If
  127.         nRemoteIP = Nothing
  128.  
  129.         GC.Collect()
  130.     End Sub
  131.     Public Function Listen(ByVal Port As Int32) As Boolean
  132.         If Listening OrElse Connected OrElse Connecting Then Return False
  133.  
  134.         Try
  135.             StopEverything()
  136.             TcpListener = New Net.Sockets.TcpListener(Net.IPAddress.Any, Port)
  137.             TcpListener.ExclusiveAddressUse = False
  138.             TcpListener.Start()
  139.  
  140.             If BWListener IsNot Nothing Then BWListener.Dispose()
  141.             BWListener = New System.ComponentModel.BackgroundWorker
  142.             BWListener.WorkerReportsProgress = True
  143.             BWListener.WorkerSupportsCancellation = True
  144.             BWListener.RunWorkerAsync()
  145.         Catch ex As Exception
  146.             Return False
  147.         End Try
  148.  
  149.         Return True
  150.     End Function
  151.     ''' <summary>
  152.     ''' Sends serialized object. All the objects inside must be serializable.
  153.     ''' All the outcoming data should be located in the same root namespace as the clients'
  154.     ''' </summary>
  155.     Public Function SendData(ByVal Data As Object) As Boolean
  156.         If Data Is Nothing Then Return False
  157.         Try
  158.             'Serializing
  159.             Dim S = New BinaryFormatter, ByteData() As Byte
  160.             Using Stream = New IO.MemoryStream()
  161.                 S.Serialize(Stream, Data)
  162.                 ByteData = Stream.ToArray
  163.             End Using
  164.  
  165.             'Sending converted
  166.             SW.WriteLine(Convert.ToBase64String(ByteData))
  167.             SW.Flush()
  168.         Catch ex As Exception
  169.             Return False
  170.         Finally
  171.             GC.Collect()
  172.         End Try
  173.         Return True
  174.     End Function
  175.  
  176.     Private Sub BWListener_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWListener.DoWork
  177.         'Listening until it comes
  178.         Try
  179.             Do
  180.                 Threading.Thread.Sleep(100)
  181.             Loop Until TcpListener.Pending Or BWListener.CancellationPending
  182.  
  183.             If TcpListener.Pending Then
  184.                 e.Result = TcpListener.AcceptTcpClient
  185.                 TcpListener.Stop()
  186.             End If
  187.         Catch ex As Exception
  188.             e.Result = Nothing
  189.         End Try
  190.     End Sub
  191.     Private Sub BWListener_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWListener.RunWorkerCompleted
  192.         If e.Result Is Nothing Then Return
  193.  
  194.         'Got a connection!
  195.         Dim TcpClient = CType(e.Result, Net.Sockets.TcpClient)
  196.         StopEverything()
  197.  
  198.         Me.TcpClient = TcpClient
  199.         nRemoteIP = Me.TcpClient.Client.LocalEndPoint
  200.         NS = TcpClient.GetStream
  201.         SW = New IO.StreamWriter(NS)
  202.         RaiseEvent OnClientAccept(Me)
  203.  
  204.         RunReceiver()
  205.     End Sub
  206.  
  207.     Private Sub RunReceiver()
  208.         If BWReceiver IsNot Nothing Then
  209.             BWReceiver.CancelAsync()
  210.             BWReceiver.Dispose()
  211.         End If
  212.  
  213.         AliveSender(False)
  214.  
  215.         BWReceiver = New System.ComponentModel.BackgroundWorker
  216.         BWReceiver.WorkerSupportsCancellation = True
  217.         BWReceiver.WorkerReportsProgress = True
  218.         BWReceiver.RunWorkerAsync()
  219.     End Sub
  220.  
  221.     Private Sub AliveSender(Optional ByVal DoIt As Boolean = True)
  222.         If Timeouted Then
  223.             StopEverything()
  224.         Else
  225.             'Registers slow-bomb pseudo-recursia on this procedure %)
  226.             Helper.RunIn(AddressOf AliveSender, 15000)
  227.  
  228.             'Sends keep-alive packet if we are already in
  229.             If DoIt AndAlso Connected Then SW.WriteLine("StayAliveMan")
  230.         End If
  231.     End Sub
  232.  
  233.     Private ReadOnly Property Timeouted() As Boolean
  234.         Get
  235.             Return nLastAliveMsg.ElapsedMilliseconds > TimeoutIntervalMs
  236.         End Get
  237.     End Property
  238.  
  239.     Private Sub BWReceiver_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWReceiver.DoWork
  240.         TcpClient.Client.LingerState.LingerTime = 1000
  241.         TcpClient.Client.LingerState.Enabled = True
  242.  
  243.         Using SR = New IO.StreamReader(NS)
  244.             Try
  245.                 Do
  246.                     'Hanging until we got a string &
  247.                     'Reporting received data
  248.                     If NS.DataAvailable Then BWReceiver.ReportProgress(0, SR.ReadLine) Else Threading.Thread.Sleep(100)
  249.                 Loop Until BWReceiver.CancellationPending Or Not Connected Or Timeouted
  250.             Catch ex As Exception
  251.                 'Connection lost
  252.                 e.Result = ex
  253.             End Try
  254.         End Using
  255.     End Sub
  256.     Private Sub BWReceiver_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BWReceiver.ProgressChanged
  257.         Dim Data = CType(e.UserState, String)
  258.         If Data Is Nothing Then Return
  259.         If TypeOf Data Is String AndAlso Data = "StayAliveMan" Then
  260.             nLastAliveMsg = Stopwatch.StartNew
  261.             Return
  262.         End If
  263.  
  264.         Try
  265.             Dim S = New BinaryFormatter
  266.             'Unconvert
  267.             Dim ByteData = Convert.FromBase64String(Data)
  268.             'Deserialize
  269.             Using Stream = New IO.MemoryStream(ByteData, False)
  270.                 RaiseEvent OnDataReceive(Me, S.Deserialize(Stream))
  271.             End Using
  272.         Catch ex As Exception
  273.             Throw New Exception(String.Format("Deserialization failed: {0}{0}{1}", vbNewLine, ex.Message))
  274.         Finally
  275.             GC.Collect()
  276.         End Try
  277.     End Sub
  278.     Private Sub BWReceiver_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWReceiver.RunWorkerCompleted
  279.         If BWReceiver IsNot Nothing Then BWReceiver.Dispose()
  280.         StopEverything()
  281.         RaiseEvent OnConnectionLost(Me)
  282.     End Sub
  283.  
  284.     Private Sub BWConnector_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWConnector.DoWork
  285.         Dim Address = CType(e.Argument(0), String)     'ip
  286.         Dim Port = CType(e.Argument(1), Int32)         'port
  287.         Try
  288.             Dim TcpClient = New Net.Sockets.TcpClient
  289.             TcpClient.Connect(Address, Port)
  290.             If TcpClient.Connected Then e.Result = TcpClient Else e.Result = Nothing
  291.         Catch ex As Exception
  292.             e.Result = ex
  293.         End Try
  294.     End Sub
  295.     Private Sub BWConnector_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWConnector.RunWorkerCompleted
  296.         If BWConnector Is Nothing Then Return
  297.         StopEverything()
  298.  
  299.         'if we really connected
  300.         If TypeOf e.Result Is Net.Sockets.TcpClient Then
  301.             TcpClient = e.Result
  302.             NS = TcpClient.GetStream
  303.             SW = New IO.StreamWriter(NS)
  304.             nRemoteIP = CType(TcpClient.Client.RemoteEndPoint, Net.IPEndPoint)
  305.             RaiseEvent OnConnect(Me)
  306.             RunReceiver()
  307.         Else
  308.             RaiseEvent OnConnectFail(Me)
  309.         End If
  310.  
  311.     End Sub
  312.  
  313.     ' IDisposable
  314.     Protected Overridable Sub Dispose(ByVal disposing As Boolean)
  315.         If Not Me.disposedValue Then
  316.             If disposing Then
  317.                 ' TODO: free other state (managed objects).
  318.                 StopEverything()
  319.             End If
  320.  
  321.             ' TODO: free your own state (unmanaged objects).
  322.             ' TODO: set large fields to null.
  323.         End If
  324.         Me.disposedValue = True
  325.     End Sub
  326.  
  327. #Region " IDisposable Support "
  328.     Private disposedValue As Boolean = False 'To detect redundant calls
  329.  
  330.     ' This code added by Visual Basic to correctly implement the disposable pattern.
  331.     Public Sub Dispose() Implements IDisposable.Dispose
  332.         ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
  333.         Dispose(True)
  334.         GC.SuppressFinalize(Me)
  335.     End Sub
  336. #End Region
  337.  
  338. End Class

Ответить

Номер ответа: 14
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #14 Добавлено: 22.09.10 15:57
кстати, ув. гуру, привлекаю ваше внимание дабы дать вам возможность пораскинуть мозгами самими и усовершенстсовать сий код в частности. можно частями, желательно, маленькими

Ответить

Номер ответа: 15
Автор ответа:
 EROS



Вопросов: 58
Ответов: 4255
 Профиль | | #15 Добавлено: 22.09.10 21:31
ТС, код класса UserConnection в студию
AgentFire, первое что бросается в глаза это BackgroundWorker.. настоящие джедаи его не юзают.
во вторых.. GC.Collect() - это что такое??? Кто тебя такому научил?
в третьих.. у тебя RunIn объвляена как Shared.. зачем? Параметры правильнее было бы передать в конструкторе.

остальное не смотрел.. от синтаксиса VB у меня мигрень начинается.

Ответить

Страница: 1 | 2 | 3 | 4 | 5 | 6 |

Поиск по форуму



© Copyright 2002-2011 VBNet.RU | Пишите нам