2010年12月7日 星期二

vbnet socket 傳送文件

服务端:
Imports System.Text '
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Form1
Dim socket As Socket
Delegate Sub setText(ByVal text As String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim localEndPoint As New IPEndPoint(Net.IPAddress.Parse("172.17.53.90"), 9999)
socket.Bind(localEndPoint)
socket.Listen(3)
SetLableText("~~~~~~~~~~~~服务已开始启动~~~~~~~~~~~~~~")
While True
Dim fileStream As FileStream = New FileStream("mytest.doc", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim byteArray(6553500) As Byte
Dim binary As New BinaryWriter(fileStream)
Dim receiveSocket As Socket = socket.Accept()
receiveSocket.Receive(byteArray)
binary.Write(byteArray, 0, byteArray.Length - 1)
receiveSocket.Shutdown(SocketShutdown.Receive)
FileStream.Close()
receiveSocket.Close()
End While


End Sub
Private Sub SetLableText(ByVal txt As String)

If Label1.InvokeRequired Then
Dim st As setText = New setText(AddressOf SetLableText)
Me.Invoke(st, New Object() {txt})
Else
Label1.Text = txt
End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Label1.Text = "淡淡的"
End Sub
End Class
客户端:
Imports System.Text
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Form1
Dim fileName = ""
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All Documents(*.*)|*.*|Word Documents|*.doc"
OpenFileDialog1.FilterIndex = 1
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.InitialDirectory = "c:\"

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
fileName = OpenFileDialog1.FileName
End If
TextBox1.Text = fileName
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sendSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim endPoint As New IPEndPoint(Net.IPAddress.Parse("172.17.53.90"), 9999)
sendSocket.Connect(endPoint)
Dim file As FileStream = New FileStream(TextBox1.Text, FileMode.Open)
Dim binaryRead As New BinaryReader(file)
Dim byteArray(file.Length - 1) As Byte
binaryRead.Read(byteArray, 0, file.Length - 1)
sendSocket.Send(byteArray)
file.Close()
sendSocket.Shutdown(SocketShutdown.Send)
sendSocket.Close()
Label2.Text = "文档已经创送完毕!"
End Sub
End Class

沒有留言:

張貼留言