我想要一個VB.net(快遞2010)應用程序連接到套接字服務器(保持連接打開),我會怎麼做呢?現在它使用Flash XMLsocket,我試圖用現有的服務器構建一個沒有Flash的新客戶端。VB.net閃存XMLSocket替換應用程序
目前我只是使用一個簡單的窗口顯示消息,以及一個地方發送消息。
它說我已連接,但它不顯示消息,並且當我使用相同的IP和端口telnet到服務器時,發送的消息看起來沒有任何作用,所以我可以看到消息進入我的系統知道我可以連接到服務器。這裏是我的代碼:
Imports System.Text
Imports System.Net.Sockets
Public Class Form1
Inherits System.Windows.Forms.Form
Public Delegate Sub DisplayInvoker(ByVal t As String)
Private mobjClient As TcpClient
Private marData(1024) As Byte
Private mobjText As New StringBuilder()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
mobjClient = New TcpClient("example.com", 7777)
DisplayText("Connected to host " & "example.com")
mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Send(txtSend.Text)
txtSend.Text = ""
End Sub
Private Sub Send(ByVal t As String)
Dim w As New IO.StreamWriter(mobjClient.GetStream)
w.Write(t & vbCr)
w.Flush()
DisplayText(vbNewLine & "Sent " & t)
End Sub
Private Sub DoRead(ByVal ar As IAsyncResult)
Dim intCount As Integer
Try
intCount = mobjClient.GetStream.EndRead(ar)
If intCount < 1 Then
MarkAsDisconnected()
Exit Sub
End If
BuildString(marData, 0, intCount)
mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
Catch e As Exception
MarkAsDisconnected()
End Try
End Sub
Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer)
Dim intIndex As Integer
For intIndex = offset To offset + count - 1
If Bytes(intIndex) = 10 Then
mobjText.Append(vbLf)
Dim params() As Object = {mobjText.ToString}
Me.Invoke(New DisplayInvoker(AddressOf Me.DisplayText), params)
mobjText = New StringBuilder()
Else
mobjText.Append(ChrW(Bytes(intIndex)))
End If
Next
End Sub
Private Sub MarkAsDisconnected()
txtSend.ReadOnly = True
btnSend.Enabled = False
DisplayText(vbNewLine & "Dissconnected")
End Sub
Private Sub DisplayText(ByVal t As String)
txtDisplay.AppendText(t)
End Sub
End Class
雞蛋裏挑骨頭:客戶通常連接到服務器,而不是周圍的其他方式。 FTP例外的一些協議允許服務器打開輔助套接字進行數據傳輸。 – cHao 2010-08-20 02:57:52
XmlSocket部分似乎特別相關,因爲它定義了使用的協議,但遠程服務器的語言/平臺無關緊要。不過,它確實增加了一些重要的理由,那就是你應該使用像UTF-8這樣的編碼來解碼字符串,而不是假設每個字節都是一個字符(這種情況很少出現)。 – cHao 2010-08-20 15:13:19