#2
moou2018-08-28 16:07
找了段之前在网上保存的代码,你看看对比一下吧 我测试没啥问题
程序代码: Imports Imports Imports System.Text Imports System.Threading Public Class Form1 Dim s As Socket = Nothing Dim t As Thread Public Sub WaitData() Dim serverAddress As String = ipText.Text() s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用TCP协议 Dim localEndPoint As New IPEndPoint(IPAddress.Parse(serverAddress), 1024) '指定IP和Port s.Bind(localEndPoint) '绑定到该Socket s.Listen(100) '侦听,最多接受100个连接 While (True) Dim bytes(1024) As Byte '用来存储接收到的字节 Dim ss As Socket = s.Accept() '若接收到,则创建一个新的Socket与之连接 ss.Receive(bytes) '接收数据,若用ss.send(Byte()),则发送数据 ListBox1.Items.Insert(0, Encoding.Unicode.GetString(bytes)) '将其插入到列表框的第一项之前,若使用Encoding.ASCII.GetString(bytes),则接收到的中文字符不能正常显示 End While End Sub Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click t = New Thread(AddressOf WaitData) '建立新的线程 t.Start() '启动线程 BtnStart.Enabled = False '按钮不可用,避免另启线程 End Sub Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click Try s.Close() '关闭Socket t.Abort() '中止线程 Catch Finally BtnStart.Enabled = True '启用BtnStart End Try End Sub Private Sub Form1_closed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Closed Try s.Close() t.Abort() Catch End Try End Sub End Class |
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