VB.Net Tutorial/Socket Network/Socket Server — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 16:40, 26 мая 2010
Содержание
Date time server based on System.Net.Sockets.Socket
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class DateTimeServer
Public Shared Sub Main()
Dim serverSocket As System.Net.Sockets.Socket
Try
Dim hostname As String = Dns.GetHostName()
Dim serverIP As IPAddress = Dns.Resolve(hostname).AddressList(0)
Dim Port As String = "13"
Dim serverhost As New IPEndPoint(serverIP, Int32.Parse(Port))
serverSocket = New Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)
serverSocket.Bind(serverhost)
serverSocket.Listen(50)
Console.WriteLine("DateTime server started at: " + serverhost.Address.ToString() + ":" + Port)
Dim lc As New ListenClient(serverSocket)
Dim serverthread As New Thread(New ThreadStart(AddressOf lc.ServerThreadProc))
serverthread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
End Class
Public Class ListenClient
Private serverSocket As System.Net.Sockets.Socket
Public Sub New(ByVal serverSocket As System.Net.Sockets.Socket)
Me.serverSocket = serverSocket
End Sub
Public Sub ServerThreadProc()
Dim clientSocket As System.Net.Sockets.Socket
Try
While (True)
clientSocket = serverSocket.Accept()
Dim clientInfo As IPEndPoint = CType( _
clientSocket.RemoteEndPoint, _
IPEndPoint)
Dim serverInfo As IPEndPoint = CType( _
serverSocket.LocalEndPoint, _
IPEndPoint)
Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString())
Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString())
Dim strDate As String = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString()
Dim byteDateLine() As Byte = Encoding.ASCII.GetBytes(strDate.ToCharArray())
clientSocket.Send(byteDateLine, byteDateLine.Length, SocketFlags.None)
Console.WriteLine("To Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString() + ": " + strDate)
clientSocket.Shutdown(SocketShutdown.Both)
clientSocket.Close()
End While
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End Sub
End Class
Socket server
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Public Class ServerSocket
Public Shared Sub Main()
Try
Dim serverSocket As New Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)
Dim serverIP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim Port As String = "80"
Dim serverhost As New IPEndPoint(serverIP, Int32.Parse(Port))
serverSocket.Bind(serverhost)
serverSocket.Listen(50)
Console.WriteLine("Server started at: " + serverIP.ToString() + ":" + Port)
Dim lc As New ListenClient(serverSocket)
Dim serverthread As New Thread(New ThreadStart(AddressOf lc.ServerThreadProc))
serverthread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
End Class
Public Class ListenClient
Private serverSocket As System.Net.Sockets.Socket
Private clientSocket As System.Net.Sockets.Socket
Public Sub New(ByVal serverSocket As System.Net.Sockets.Socket)
Me.serverSocket = serverSocket
End Sub
Public Sub ServerThreadProc()
Do While True
Try
Dim clientSocket As Socket = serverSocket.Accept()
Dim clientInfo As IPEndPoint = CType( _
clientSocket.RemoteEndPoint, _
IPEndPoint)
Dim serverInfo As IPEndPoint = CType( _
serverSocket.LocalEndPoint, _
IPEndPoint)
Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString())
Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString())
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
Loop
End Sub
End Class
Server started at: 127.0.0.1:80 ^CTerminate batch job (Y/N)? n
Socket Server with user interface
Imports System.Text
Imports System.Net.Sockets
Imports System.Threading
Imports System.Windows.Forms
public class SocketServerUI
public Shared Sub Main
Application.Run(New Form1)
End Sub
End class
Public Class Form1
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ruponentModel.IContainer
Friend WithEvents btnListener As System.Windows.Forms.Button
Friend WithEvents lblMessage As System.Windows.Forms.Label
Friend WithEvents lblConnection As System.Windows.Forms.Label
Friend WithEvents lblPort As System.Windows.Forms.Label
Friend WithEvents txtPort As System.Windows.Forms.TextBox
Friend WithEvents btnClose As System.Windows.Forms.Button
Friend WithEvents txtContent As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents btnWrite As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.btnListener = New System.Windows.Forms.Button()
Me.lblMessage = New System.Windows.Forms.Label()
Me.lblConnection = New System.Windows.Forms.Label()
Me.lblPort = New System.Windows.Forms.Label()
Me.txtPort = New System.Windows.Forms.TextBox()
Me.btnClose = New System.Windows.Forms.Button()
Me.txtContent = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.btnWrite = New System.Windows.Forms.Button()
Me.SuspendLayout()
"
"btnListener
"
Me.btnListener.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnListener.Location = New System.Drawing.Point(338, 28)
Me.btnListener.Name = "btnListener"
Me.btnListener.Size = New System.Drawing.Size(113, 32)
Me.btnListener.TabIndex = 0
Me.btnListener.Text = "Start Listening"
"
"lblMessage
"
Me.lblMessage.BackColor = System.Drawing.Color.White
Me.lblMessage.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.lblMessage.Location = New System.Drawing.Point(164, 80)
Me.lblMessage.Name = "lblMessage"
Me.lblMessage.Size = New System.Drawing.Size(389, 24)
Me.lblMessage.TabIndex = 1
"
"lblConnection
"
Me.lblConnection.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.lblConnection.Location = New System.Drawing.Point(61, 80)
Me.lblConnection.Name = "lblConnection"
Me.lblConnection.Size = New System.Drawing.Size(93, 24)
Me.lblConnection.TabIndex = 2
Me.lblConnection.Text = "Connection Message"
"
"lblPort
"
Me.lblPort.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.lblPort.Location = New System.Drawing.Point(41, 33)
Me.lblPort.Name = "lblPort"
Me.lblPort.Size = New System.Drawing.Size(113, 24)
Me.lblPort.TabIndex = 3
Me.lblPort.Text = "Port"
"
"txtPort
"
Me.txtPort.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.txtPort.Location = New System.Drawing.Point(164, 31)
Me.txtPort.Name = "txtPort"
Me.txtPort.Size = New System.Drawing.Size(133, 26)
Me.txtPort.TabIndex = 4
Me.txtPort.Text = ""
"
"btnClose
"
Me.btnClose.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnClose.Location = New System.Drawing.Point(471, 27)
Me.btnClose.Name = "btnClose"
Me.btnClose.Size = New System.Drawing.Size(102, 32)
Me.btnClose.TabIndex = 5
Me.btnClose.Text = "Stop Connection"
"
"txtContent
"
Me.txtContent.Location = New System.Drawing.Point(164, 120)
Me.txtContent.Multiline = True
Me.txtContent.Name = "txtContent"
Me.txtContent.Size = New System.Drawing.Size(389, 88)
Me.txtContent.TabIndex = 6
Me.txtContent.Text = ""
"
"Label1
"
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.Label1.Location = New System.Drawing.Point(61, 120)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(93, 24)
Me.Label1.TabIndex = 7
Me.Label1.Text = "Data"
"
"btnWrite
"
Me.btnWrite.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnWrite.Location = New System.Drawing.Point(573, 120)
Me.btnWrite.Name = "btnWrite"
Me.btnWrite.Size = New System.Drawing.Size(123, 32)
Me.btnWrite.TabIndex = 8
Me.btnWrite.Text = "Write"
"
"Form1
"
Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
Me.ClientSize = New System.Drawing.Size(716, 261)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnWrite, Me.Label1, Me.txtContent, Me.btnClose, Me.txtPort, Me.lblPort, Me.lblConnection, Me.lblMessage, Me.btnListener})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Dim intPort As Integer
Dim myTcpListener As TcpListener
Dim myNetworkStream As NetworkStream
Private Sub btnListener_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListener.Click
Dim myThread As New Thread(New ThreadStart(AddressOf StartListen))
myThread.Start()
End Sub
Private Sub StartListen()
intPort = Integer.Parse(txtPort.Text)
myTcpListener = New TcpListener(intPort)
Dim blnConection As Boolean = False
Try
myTcpListener.Start()
lblMessage.Text = "Waiting..."
Dim mySocket As Socket = myTcpListener.AcceptSocket()
Do
If mySocket.Connected = True Then
lblMessage.Text = "Port: " + txtPort.Text + "Connected"
myNetworkStream = New NetworkStream(mySocket)
Dim strContent As String
Dim lngByte As Long = myNetworkStream.ReadByte()
Dim myByte(lngByte) As Byte
myNetworkStream.Read(myByte, 0, lngByte)
strContent = Encoding.ASCII.GetString(myByte, 0, lngByte)
txtContent.Text = strContent
End If
Loop
Catch ex As SocketException
MessageBox.Show _
(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
myTcpListener.Stop()
End Sub
Private Sub btnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWrite.Click
Dim strTest As String = txtContent.Text
Dim myBytes() As Byte = Encoding.ASCII.GetBytes(strTest)
lblMessage.Text = ("Message")
myNetworkStream.Write(myBytes, 0, myBytes.Length)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Using Async Socket Server
Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.Windows.Forms
public class UsingAsyncSocketServer
public Shared Sub Main
Application.Run(New Form1)
End Sub
End class
Public Class Form1
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ruponentModel.IContainer
Friend WithEvents btnListener As System.Windows.Forms.Button
Friend WithEvents lblConnection As System.Windows.Forms.Label
Friend WithEvents lblPort As System.Windows.Forms.Label
Friend WithEvents txtPort As System.Windows.Forms.TextBox
Friend WithEvents btnClose As System.Windows.Forms.Button
Friend WithEvents btnReceive As System.Windows.Forms.Button
Friend WithEvents txtMessage As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents btnSend As System.Windows.Forms.Button
Friend WithEvents txtAccept As System.Windows.Forms.TextBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.btnListener = New System.Windows.Forms.Button()
Me.lblConnection = New System.Windows.Forms.Label()
Me.lblPort = New System.Windows.Forms.Label()
Me.txtPort = New System.Windows.Forms.TextBox()
Me.btnClose = New System.Windows.Forms.Button()
Me.btnReceive = New System.Windows.Forms.Button()
Me.txtMessage = New System.Windows.Forms.TextBox()
Me.txtAccept = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.btnSend = New System.Windows.Forms.Button()
Me.SuspendLayout()
"
"btnListener
"
Me.btnListener.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnListener.Location = New System.Drawing.Point(338, 24)
Me.btnListener.Name = "btnListener"
Me.btnListener.Size = New System.Drawing.Size(113, 32)
Me.btnListener.TabIndex = 0
Me.btnListener.Text = "Start"
"
"lblConnection
"
Me.lblConnection.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.lblConnection.Location = New System.Drawing.Point(41, 72)
Me.lblConnection.Name = "lblConnection"
Me.lblConnection.Size = New System.Drawing.Size(92, 24)
Me.lblConnection.TabIndex = 2
Me.lblConnection.Text = "Info"
"
"lblPort
"
Me.lblPort.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.lblPort.Location = New System.Drawing.Point(20, 32)
Me.lblPort.Name = "lblPort"
Me.lblPort.Size = New System.Drawing.Size(113, 24)
Me.lblPort.TabIndex = 3
Me.lblPort.Text = "Port"
"
"txtPort
"
Me.txtPort.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.txtPort.Location = New System.Drawing.Point(143, 24)
Me.txtPort.Name = "txtPort"
Me.txtPort.Size = New System.Drawing.Size(133, 26)
Me.txtPort.TabIndex = 4
Me.txtPort.Text = "36000"
"
"btnClose
"
Me.btnClose.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnClose.Location = New System.Drawing.Point(461, 24)
Me.btnClose.Name = "btnClose"
Me.btnClose.Size = New System.Drawing.Size(102, 32)
Me.btnClose.TabIndex = 5
Me.btnClose.Text = "Stop"
"
"btnReceive
"
Me.btnReceive.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnReceive.Location = New System.Drawing.Point(276, 248)
Me.btnReceive.Name = "btnReceive"
Me.btnReceive.Size = New System.Drawing.Size(175, 32)
Me.btnReceive.TabIndex = 6
Me.btnReceive.Text = "Receive"
"
"txtMessage
"
Me.txtMessage.Location = New System.Drawing.Point(143, 72)
Me.txtMessage.Multiline = True
Me.txtMessage.Name = "txtMessage"
Me.txtMessage.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtMessage.Size = New System.Drawing.Size(430, 88)
Me.txtMessage.TabIndex = 7
Me.txtMessage.Text = ""
"
"txtAccept
"
Me.txtAccept.Location = New System.Drawing.Point(143, 168)
Me.txtAccept.Multiline = True
Me.txtAccept.Name = "txtAccept"
Me.txtAccept.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtAccept.Size = New System.Drawing.Size(430, 64)
Me.txtAccept.TabIndex = 9
Me.txtAccept.Text = ""
"
"Label1
"
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.Label1.Location = New System.Drawing.Point(10, 168)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(144, 24)
Me.Label1.TabIndex = 8
Me.Label1.Text = "Data"
"
"btnSend
"
Me.btnSend.Font = New System.Drawing.Font("Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.btnSend.Location = New System.Drawing.Point(461, 248)
Me.btnSend.Name = "btnSend"
Me.btnSend.Size = New System.Drawing.Size(112, 32)
Me.btnSend.TabIndex = 10
Me.btnSend.Text = "Data sent back"
"
"Form1
"
Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
Me.ClientSize = New System.Drawing.Size(665, 309)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnSend, Me.txtAccept, Me.Label1, Me.txtMessage, Me.btnReceive, Me.btnClose, Me.txtPort, Me.lblPort, Me.lblConnection, Me.btnListener})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Dim strMessage
Dim myListener As Socket
Dim bteAccept(65536) As Byte
Dim bteSend(65536) As Byte
Dim EndSocket As Socket
Private Sub btnListener_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListener.Click
Dim myThread As New Thread(New ThreadStart(AddressOf StartListen))
myThread.Start()
End Sub
Private Sub btnReceive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReceive.Click
Dim myThread As New Thread(New ThreadStart(AddressOf ReceiveStart))
myThread.Start()
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim myThread As New Thread(New ThreadStart(AddressOf SendStart))
myThread.Start()
End Sub
Private Sub StartListen()
Dim intPort As Integer
Dim bidEndPoint As IPEndPoint
intPort = Integer.Parse(txtPort.Text)
bidEndPoint = New IPEndPoint(IPAddress.Parse("10.2.3.127"), intPort)
myListener = New Socket _
(AddressFamily.InterNetwork, _
SocketType.Stream, _
ProtocolType.Tcp)
Try
" myListener.Bind(bidEndPoint)
Dim myAsyncCallBack As New AsyncCallback(AddressOf AcceptEnd)
myListener.Listen(intPort)
myListener.BeginAccept(myAsyncCallBack, myListener)
txtMessage.Text += vbCrLf + "Waiting"
strMessage += "//Head..." + vbCrLf
strMessage += "//Server Send Message ..." + vbCrLf
strMessage += "--------------------------------" + vbCrLf
Catch ex As SocketException
Console.WriteLine(ex.Message)
End Try
End Sub
Private Sub AcceptEnd(ByVal pIAsyncResult As IAsyncResult)
EndSocket = myListener.EndAccept(pIAsyncResult)
End Sub
Private Sub ReceiveStart()
Dim myAsyncCallBack As New AsyncCallback(AddressOf ReceiveData)
EndSocket.BeginReceive _
(bteAccept, 0, 65536, 0, _
myAsyncCallBack, EndSocket)
End Sub
Private Sub ReceiveData(ByVal pIAsyncResult As IAsyncResult)
Dim intByte As Integer
intByte = EndSocket.EndReceive(pIAsyncResult)
If intByte > 0 Then
strMessage += Encoding.ASCII.GetString(bteAccept)
txtAccept.Text = strMessage
End If
End Sub
Private Sub SendStart()
Dim myAsyncCallBack As New AsyncCallback(AddressOf SendData)
bteSend = Encoding.ASCII.GetBytes(strMessage)
EndSocket.BeginSend _
(bteSend, 0, bteSend.Length, _
SocketFlags.DontRoute, myAsyncCallBack, EndSocket)
End Sub
Private Sub SendData(ByVal pIAsyncResult As IAsyncResult)
Dim intSend As Integer
intSend = EndSocket.EndSend(pIAsyncResult)
txtMessage.Text += vbCrLf + "Data sent " + intSend.ToString + "bytes"
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
myListener.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class