vb.net 源码
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim MyTcpListener As TcpListener
Dim MyListenThread As Thread
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'关闭SOCKET
Try
If Me.MyTcpListener IsNot Nothing Then
'关闭监听器
Me.MyTcpListener.Stop()
End If
If Me.MyListenThread IsNot Nothing Then
'如果线程还处于运行状态就关闭它
If Me.MyListenThread.ThreadState <> ThreadState.Running Then
Me.MyListenThread.Abort()
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
e.Cancel = False
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' 开始监听()
'创建监听线程
Me.MyListenThread = New Thread(AddressOf StartListen)
'启动线程
Me.MyListenThread.Start()
End Sub
Private Sub StartListen()
MyTcpListener = New TcpListener(888)
'开始监听
MyTcpListener.Start()
'While (True)
'获取TcpClient
Dim MyTcpClient As TcpClient = MyTcpListener.AcceptTcpClient()
Dim MyStream As NetworkStream = MyTcpClient.GetStream()
Dim MyBytes(1024) As Byte
Dim MyBytesRead As Integer = MyStream.Read(MyBytes, 0, MyBytes.Length)
Dim MyMessage As String = System.Text.UnicodeEncoding.GetEncoding("gb2312").GetString(MyBytes, 0, MyBytesRead)
Me.RichTextBox2.AppendText(MyMessage)
'End While
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (Me.TextBox1.Text.Length < 1 Or Me.TextBox2.Text.Length < 1 Or Me.RichTextBox1.Text.Length < 1) Then
Exit Sub
End If
Try
Dim MyMessage As String = "消息来自(" + Me.TextBox2.Text + "):" + Me.RichTextBox1.Text + Chr(10) + Chr(13)
'根据目标计算机地址建立连接
Dim MyTcpClient As TcpClient = New TcpClient(Me.TextBox1.Text, 888)
'获得用于网络访问的数据流
Dim MyTcpStream As Net.Sockets.NetworkStream = MyTcpClient.GetStream()
Dim MyStream As IO.StreamWriter = New IO.StreamWriter(MyTcpStream, System.Text.UnicodeEncoding.GetEncoding("gb2312"))
'将字符串写入流
MyStream.Write(MyMessage)
'将缓冲数据写入基础流
MyStream.Flush()
'关闭网络流
MyStream.Close()
'MyTcpClient.Close()
Me.RichTextBox2.AppendText("发送:" & Me.RichTextBox1.Text)
Me.RichTextBox1.Clear()
Catch ex As Exception
MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
End Class
阅读(1074) | 评论(0) | 转发(0) |