看了别人写的,自己 改了点东西,更加实用;
Client端代码:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Net.NetworkInformation
Public Class Client
Const IP As String = "192.168.1.111" '服务端IP地址
Const Port As String = "876" '服务端端口号
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim byts(366) As Byte '创建一个Byte数组
Dim socket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim localEndPoint As New IPEndPoint(IPAddress.Parse(IP), Port)
socket.Connect(localEndPoint)
Dim allText As String = Me.TextBox1.Text + "," + TextBox2.Text '把页面上的值用","拼接使传送过去的值可以更好的分割
socket.Send(Encoding.Unicode.GetBytes(allText)) '通过Socket把值发送到对方的地址上去
socket.Close()
Catch ex As Exception
End Try
End Sub
Private Sub Client_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.Ping("192.168.1.116") Then
MsgBox("连接成功")
Else
MsgBox("连接失败")
End If
End Sub
End Class
Server端代码:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Net.NetworkInformation
Public Class Server
Dim socket As Socket = Nothing
Dim thread As Thread
Const IP As String = "192.168.1.111" '客户端IP地址
Const port As String = "876" '客户端端口号
Public Sub getSocket() ' 创建一个处理Socket包的方法
socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '传输方式
Dim localEndPoint As New IPEndPoint(IPAddress.Parse(IP), port) '指定IP和Port
socket.Bind(localEndPoint) '绑定到该Socket
socket.Listen(100) '最多监听100个链接
While (True)
Dim byts(366) As Byte '用来存储接收到的字节
Dim getSocket As Socket = socket.Accept '若接收到,则创建一个新的Socket与之连接
getSocket.Receive(byts) '接收数据,若用socket.send(Byte()),则发送数据
Dim a() As String = Encoding.Unicode.GetString(byts).Split(",") '将所得到的值用","号隔开
For Each i In a
ListBox1.Items.Insert(0, i.ToString) '一次把值插入到listbox中
Next
End While
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
thread = New Thread(AddressOf getSocket) '建立新的线程
thread.Start() '开启线程
Me.Button1.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
socket.Close()
thread.Abort()
Catch ex As Exception
Finally
Me.Button2.Enabled = False
End Try
End Sub
Private Sub Server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.Ping("192.168.1.116") Then
MsgBox("连接成功")
Else
MsgBox("连接失败")
End If
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class