Страница: 1 | 2 | 3 | 4 | 5 | 6 |
Вопрос: русские буквы
Добавлено: 21.09.10 15:53
Автор вопроса: Ishayahu | Web-сайт: ishayahu.blogspot.com | ICQ: 329944992
есть программа для работы через сеть . при посылке английского текста все работает замечательно, но при пересылке русского приходят одни лишь вопросы. как это можно исправить?
Ответить
Номер ответа: 9Автор ответа: Ishayahu
ICQ: 329944992 Вопросов: 4Ответов: 21
Web-сайт: ishayahu.blogspot.com Профиль | | #9
Добавлено: 22.09.10 10:49
загрузка формы
Private Sub frmMain_Load(ByVal sender As System.Object , ByVal e As System.EventArgs) Handles MyBase .Load
Dim pc As String = Environment.MachineName
pc.ToUpper()
If pc = "COMPY" Or pc = "COMPX" Or pc = "IT-COMP-Y" Then
txtDisplay.Enabled = True
txtSend.Enabled = True
btnSend.Enabled = True
Else
txtDisplay.Enabled = False
txtSend.Enabled = False
btnSend.Enabled = False
End If
txtDisplay.Text = Environment.MachineName
Dim frmConnectUser As New frmConnectUser()
Try
client = New TcpClient("1-509" , PORT_NUM)
client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing )
Me .Show()
AttemptLogin()
Catch Ex As Exception
MsgBox("Server is not active. Please start server and try again." , _
MsgBoxStyle.Exclamation, Me .Text)
Me .Dispose()
End Try
End Sub
посылка данных
Private Sub SendData(ByVal data As String )
Dim writer As New IO.StreamWriter(client.GetStream)
writer.Write(data & vbCr)
writer.Flush()
End Sub
прием данных
Private Sub DoRead(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String
Try
BytesRead = client.GetStream.EndRead(ar)
If BytesRead < 1 Then
MarkAsDisconnected()
Exit Sub
End If
strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 2)
ProcessCommands(strMessage)
client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing )
Catch e As Exception
MarkAsDisconnected()
End Try
End Sub
Ответить
Номер ответа: 12Автор ответа: Ishayahu
ICQ: 329944992 Вопросов: 4Ответов: 21
Web-сайт: ishayahu.blogspot.com Профиль | | #12
Добавлено: 22.09.10 15:15
EROS спасибо
теперь осталась другая проблема - сообщения, которые приходят на сервер (выше был код клиента) все равно отображают вопросы, но там я ничего подобного кодировке не нашел. помогите еще раз!
Const PORT_NUM As Integer = 10000
Dim strprint As String
Private clients As New Hashtable()
Private listener As TcpListener
Private listenerThread As Threading.Thread
Private Sub Broadcast(ByVal strMessage As String )
Dim client As UserConnection
Dim entry As DictionaryEntry
For Each entry In clients
client = CType (entry.Value, UserConnection)
client.SendData(strMessage)
Next
End Sub
Private Sub btnBroadcast_Click(ByVal sender As System.Object , ByVal e As System.EventArgs) Handles btnBroadcast.Click
If txtBroadcast.Text <> "" Then
UpdateStatus("Broadcasting: " & txtBroadcast.Text)
Broadcast("BROAD|" & txtBroadcast.Text)
txtBroadcast.Text = ""
End If
End Sub
Private Sub ConnectUser(ByVal userName As String , ByVal sender As UserConnection)
If clients.Contains(userName) Then
ReplyToSender("REFUSE" , sender)
Else
sender.Name = userName
UpdateStatus(userName & " has joined the chat." )
clients.Add(userName, sender)
ReplyToSender("JOIN" , sender)
SendToClients("CHAT|" & sender.Name & " has joined the chat." , sender)
End If
End Sub
Private Sub DisconnectUser(ByVal sender As UserConnection)
UpdateStatus(sender.Name & " has left the chat." )
SendToClients("CHAT|" & sender.Name & " has left the chat." , sender)
clients.Remove(sender.Name)
End Sub
Private Sub DoListen()
Try
listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
listener.Start()
Do
Dim client As New UserConnection(listener.AcceptTcpClient)
AddHandler client.LineReceived, AddressOf OnLineReceived
UpdateStatus("New connection found: waiting for log-in" )
Loop Until False
Catch
End Try
End Sub
Private Sub frmMain_Closing(ByVal sender As Object , ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase .Closing
listener.Stop ()
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object , ByVal e As System.EventArgs) Handles MyBase .Load
listenerThread = New Threading.Thread(AddressOf DoListen)
listenerThread.Start()
UpdateStatus("Listener started" )
listtemp.Hide()
txtstatus.Hide()
End Sub
Private Sub ListUsers(ByVal sender As UserConnection)
Dim client As UserConnection
Dim entry As DictionaryEntry
Dim strUserList As String
UpdateStatus("Sending " & sender.Name & " a list of users online." )
strUserList = "LISTUSERS"
For Each entry In clients
client = CType (entry.Value, UserConnection)
strUserList = strUserList & "|" & client.Name
Next
ReplyToSender(strUserList, sender)
End Sub
Private Sub OnLineReceived(ByVal sender As UserConnection, ByVal data As String )
Dim dataArray() As String
dataArray = data.Split(Chr(124))
Select Case dataArray(0)
Case "CONNECT"
ConnectUser(dataArray(1), sender)
Case "CHAT"
SendChat(dataArray(1), sender)
Case "DISCONNECT"
DisconnectUser(sender)
Case "REQUESTUSERS"
ListUsers(sender)
Case "SRV"
UpdateStatus("|" & dataArray(1))
Case Else
UpdateStatus("Unknown message:" & data)
End Select
End Sub
Private Sub ReplyToSender(ByVal strMessage As String , ByVal sender As UserConnection)
sender.SendData(strMessage)
End Sub
Private Sub SendChat(ByVal message As String , ByVal sender As UserConnection)
UpdateStatus(sender.Name & ": " & message)
SendToClients("CHAT|" & sender.Name & ": " & message, sender)
End Sub
Private Sub SendToClients(ByVal strMessage As String , ByVal sender As UserConnection)
Dim client As UserConnection
Dim entry As DictionaryEntry
For Each entry In clients
client = CType (entry.Value, UserConnection)
If client.Name <> sender.Name Then
client.SendData(strMessage)
End If
Next
End Sub
End Class
Ответить
Номер ответа: 13Автор ответа: AgentFire
ICQ: 192496851 Вопросов: 75Ответов: 3178
Профиль | | #13
Добавлено: 22.09.10 15:53
юзай нормальные способы работы с сетью. у тебя как минимум с памятью проблемы будут огромные..
вот тебе мой личный класс да личное использование. не забывай ему вызывать Dispose в конце.
Public Class Winsock
Implements IDisposable
Public Class Helper
Private WaitMs As UInt64
Private Procedure As Threading.ThreadStart
Public Shared Sub RunIn(ByVal Procedure As Threading.ThreadStart, ByVal TimeMs As UInt64, Optional ByVal Parameters As Object = Nothing )
Dim I As New Helper
I.WaitMs = TimeMs
I.Procedure = Procedure
Dim BW = New BackgroundWorker
AddHandler BW.DoWork, AddressOf I.BW_Go
AddHandler BW.RunWorkerCompleted, AddressOf I.BW_Done
BW.RunWorkerAsync(Parameters)
End Sub
Private Sub BW_Go(ByVal sender As Object , ByVal e As DoWorkEventArgs)
e.Result = e.Argument
For i As UInt64 = 1 To WaitMs Step Int32.MaxValue
Dim WaitInterval = If (WaitMs - i > Int32.MaxValue, Int32.MaxValue, Convert.ToInt32(WaitMs - i))
Threading.Thread.Sleep(WaitInterval)
Next
End Sub
Private Sub BW_Done(ByVal sender As Object , ByVal e As RunWorkerCompletedEventArgs)
Procedure.Invoke()
CType (sender, BackgroundWorker).Dispose()
End Sub
End Class
Friend Const TimeoutIntervalMs As UInt64 = 30000
Public Event OnDataReceive(ByVal Sender As Winsock, ByVal Data As Object )
Public Event OnConnect(ByVal Sender As Winsock)
Public Event OnClientAccept(ByVal Sender As Winsock)
Public Event OnConnectionLost(ByVal Sender As Winsock)
Public Event OnConnectFail(ByVal Sender As Winsock)
Private TcpListener As Net.Sockets.TcpListener
Private TcpClient As Net.Sockets.TcpClient
Private WithEvents BWListener, BWReceiver, BWConnector As BackgroundWorker
Private nRemoteIP As Net.IPEndPoint
Private NS As Net.Sockets.NetworkStream, SW As IO.StreamWriter
Private nLastAliveMsg As New Stopwatch
Public ReadOnly Property LocalIPAddresses() As IEnumerable(Of Net.IPAddress)
Get
Return From ni In NetworkInterface.GetAllNetworkInterfaces() _
Where ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback _
From ipAddress In ni.GetIPProperties.UnicastAddresses _
Select ipAddress.Address
End Get
End Property
Public ReadOnly Property RemoteIPAddress() As Net.IPAddress
Get
Return If (nRemoteIP Is Nothing , Nothing , nRemoteIP.Address)
End Get
End Property
Public ReadOnly Property Listening() As Boolean
Get
Return BWListener IsNot Nothing AndAlso BWListener.IsBusy
End Get
End Property
Public ReadOnly Property Connecting() As Boolean
Get
Return TcpClient IsNot Nothing AndAlso Not TcpClient.Client.Connected
End Get
End Property
Public ReadOnly Property Connected() As Boolean
Get
Return TcpClient IsNot Nothing AndAlso TcpClient.Connected
End Get
End Property
Public Function Connect(ByVal Address As String , ByVal Port As Int32) As Boolean
Try
StopEverything()
TcpClient = New Net.Sockets.TcpClient
BWConnector = New System.ComponentModel.BackgroundWorker
BWConnector.WorkerSupportsCancellation = True
BWConnector.RunWorkerAsync(New Object () {Address, Port})
Catch ex As Exception
Return False
End Try
Return True
End Function
Private Sub StopBW(ByRef BWs As IEnumerable(Of BackgroundWorker))
For Each iBW In BWs.Where(Function (T) T IsNot Nothing )
StopBW(iBW)
Next
End Sub
Private Sub StopBW(ByRef BW As BackgroundWorker)
BW.CancelAsync()
BW.Dispose()
BW = Nothing
End Sub
Public Sub StopEverything()
If SW IsNot Nothing Then
SW.Close()
SW.Dispose()
End If
If NS IsNot Nothing Then
NS.Close()
NS.Dispose()
End If
StopBW(New BackgroundWorker() {BWReceiver, BWListener, BWConnector})
If TcpListener IsNot Nothing Then
TcpListener.Stop ()
TcpListener.Server.Close()
TcpListener = Nothing
End If
If TcpClient IsNot Nothing Then
TcpClient.Close()
TcpClient = Nothing
End If
nRemoteIP = Nothing
GC.Collect()
End Sub
Public Function Listen(ByVal Port As Int32) As Boolean
If Listening OrElse Connected OrElse Connecting Then Return False
Try
StopEverything()
TcpListener = New Net.Sockets.TcpListener(Net.IPAddress.Any, Port)
TcpListener.ExclusiveAddressUse = False
TcpListener.Start()
If BWListener IsNot Nothing Then BWListener.Dispose()
BWListener = New System.ComponentModel.BackgroundWorker
BWListener.WorkerReportsProgress = True
BWListener.WorkerSupportsCancellation = True
BWListener.RunWorkerAsync()
Catch ex As Exception
Return False
End Try
Return True
End Function
Public Function SendData(ByVal Data As Object ) As Boolean
If Data Is Nothing Then Return False
Try
Dim S = New BinaryFormatter, ByteData() As Byte
Using Stream = New IO.MemoryStream()
S.Serialize(Stream, Data)
ByteData = Stream.ToArray
End Using
SW.WriteLine(Convert.ToBase64String(ByteData))
SW.Flush()
Catch ex As Exception
Return False
Finally
GC.Collect()
End Try
Return True
End Function
Private Sub BWListener_DoWork(ByVal sender As Object , ByVal e As DoWorkEventArgs) Handles BWListener.DoWork
Try
Do
Threading.Thread.Sleep(100)
Loop Until TcpListener.Pending Or BWListener.CancellationPending
If TcpListener.Pending Then
e.Result = TcpListener.AcceptTcpClient
TcpListener.Stop ()
End If
Catch ex As Exception
e.Result = Nothing
End Try
End Sub
Private Sub BWListener_RunWorkerCompleted(ByVal sender As Object , ByVal e As RunWorkerCompletedEventArgs) Handles BWListener.RunWorkerCompleted
If e.Result Is Nothing Then Return
Dim TcpClient = CType (e.Result, Net.Sockets.TcpClient)
StopEverything()
Me .TcpClient = TcpClient
nRemoteIP = Me .TcpClient.Client.LocalEndPoint
NS = TcpClient.GetStream
SW = New IO.StreamWriter(NS)
RaiseEvent OnClientAccept(Me )
RunReceiver()
End Sub
Private Sub RunReceiver()
If BWReceiver IsNot Nothing Then
BWReceiver.CancelAsync()
BWReceiver.Dispose()
End If
AliveSender(False )
BWReceiver = New System.ComponentModel.BackgroundWorker
BWReceiver.WorkerSupportsCancellation = True
BWReceiver.WorkerReportsProgress = True
BWReceiver.RunWorkerAsync()
End Sub
Private Sub AliveSender(Optional ByVal DoIt As Boolean = True )
If Timeouted Then
StopEverything()
Else
Helper.RunIn(AddressOf AliveSender, 15000)
If DoIt AndAlso Connected Then SW.WriteLine("StayAliveMan" )
End If
End Sub
Private ReadOnly Property Timeouted() As Boolean
Get
Return nLastAliveMsg.ElapsedMilliseconds > TimeoutIntervalMs
End Get
End Property
Private Sub BWReceiver_DoWork(ByVal sender As Object , ByVal e As DoWorkEventArgs) Handles BWReceiver.DoWork
TcpClient.Client.LingerState.LingerTime = 1000
TcpClient.Client.LingerState.Enabled = True
Using SR = New IO.StreamReader(NS)
Try
Do
If NS.DataAvailable Then BWReceiver.ReportProgress(0, SR.ReadLine) Else Threading.Thread.Sleep(100)
Loop Until BWReceiver.CancellationPending Or Not Connected Or Timeouted
Catch ex As Exception
e.Result = ex
End Try
End Using
End Sub
Private Sub BWReceiver_ProgressChanged(ByVal sender As Object , ByVal e As ProgressChangedEventArgs) Handles BWReceiver.ProgressChanged
Dim Data = CType (e.UserState, String )
If Data Is Nothing Then Return
If TypeOf Data Is String AndAlso Data = "StayAliveMan" Then
nLastAliveMsg = Stopwatch.StartNew
Return
End If
Try
Dim S = New BinaryFormatter
Dim ByteData = Convert.FromBase64String(Data)
Using Stream = New IO.MemoryStream(ByteData, False )
RaiseEvent OnDataReceive(Me , S.Deserialize(Stream))
End Using
Catch ex As Exception
Throw New Exception(String .Format("Deserialization failed: {0}{0}{1}" , vbNewLine, ex.Message))
Finally
GC.Collect()
End Try
End Sub
Private Sub BWReceiver_RunWorkerCompleted(ByVal sender As Object , ByVal e As RunWorkerCompletedEventArgs) Handles BWReceiver.RunWorkerCompleted
If BWReceiver IsNot Nothing Then BWReceiver.Dispose()
StopEverything()
RaiseEvent OnConnectionLost(Me )
End Sub
Private Sub BWConnector_DoWork(ByVal sender As Object , ByVal e As DoWorkEventArgs) Handles BWConnector.DoWork
Dim Address = CType (e.Argument(0), String )
Dim Port = CType (e.Argument(1), Int32)
Try
Dim TcpClient = New Net.Sockets.TcpClient
TcpClient.Connect(Address, Port)
If TcpClient.Connected Then e.Result = TcpClient Else e.Result = Nothing
Catch ex As Exception
e.Result = ex
End Try
End Sub
Private Sub BWConnector_RunWorkerCompleted(ByVal sender As Object , ByVal e As RunWorkerCompletedEventArgs) Handles BWConnector.RunWorkerCompleted
If BWConnector Is Nothing Then Return
StopEverything()
If TypeOf e.Result Is Net.Sockets.TcpClient Then
TcpClient = e.Result
NS = TcpClient.GetStream
SW = New IO.StreamWriter(NS)
nRemoteIP = CType (TcpClient.Client.RemoteEndPoint, Net.IPEndPoint)
RaiseEvent OnConnect(Me )
RunReceiver()
Else
RaiseEvent OnConnectFail(Me )
End If
End Sub
Protected Overridable Sub Dispose(ByVal disposing As Boolean )
If Not Me .disposedValue Then
If disposing Then
StopEverything()
End If
End If
Me .disposedValue = True
End Sub
#Region " IDisposable Support "
Private disposedValue As Boolean = False
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True )
GC.SuppressFinalize(Me )
End Sub
#End Region
End Class
Ответить
Страница: 1 | 2 | 3 | 4 | 5 | 6 |
Поиск по форуму