vb.net写的服务端代码,但只能实现单次接收数据,下次接收又得重新连,求大神帮忙看下!!
Imports Imports
Imports System.Threading
Imports System.Text
Public Class Form1
Dim Sserver As Socket = Nothing
Dim newthread As Thread
Dim newsocket As Socket
Dim bytes(1024) As Byte
Dim ii As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newthread = New Thread(AddressOf WaitData)
newthread.Start()
Button1.Enabled = False
Button2.Enabled = True
End Sub
Public Sub WaitData()
Sserver = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ip_addr As IPAddress = IPAddress.Parse(TextBox1.Text)
Dim localEP As New IPEndPoint(ip_addr, 502)
Sserver.Bind(localEP)
Sserver.Listen(100)
While (True)
Dim i As Integer
newsocket = Sserver.Accept()
i = newsocket.Receive(bytes)
Dim str As String
str = ""
If i > 0 Then
Dim j As Integer
For j = 0 To i - 1
str += CStr(bytes(j))
Next
End If
TextBox2.Text = str & ", ii=" & ii & ", i=" & i
ii += 1
' newsocket.Close()
End While
End Sub
Public Sub New()
' 此调用是 Windows 窗体设计器所必需的。
InitializeComponent()
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
' 在 InitializeComponent() 调用之后添加任何初始化。
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Sserver.Close()
newthread.Abort()
newsocket.Close()
Button1.Enabled = True
Button2.Enabled = False
TextBox2.Text = ""
End Sub
End Class