Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Private client As Socket
Private newsock As Socket
Private receiver As Thread
Private data As Byte() = New Byte(1024) {}
Public Sub New()
InitializeComponent()
End Sub
Private Sub AcceptConn(ByVal iar As IAsyncResult)
Try
Dim oldserver As Socket = DirectCast(iar.AsyncState, Socket)
client = oldserver.EndAccept(iar)
listdata.Items.Add("Connection froms: " & Convert.ToString(client.RemoteEndPoint))
receiver = New Thread(New ThreadStart(AddressOf ReceiveData))
receiver.Start()
Catch
End Try
End Sub
Private Sub ReceiveData()
Dim recv As Integer
Dim strData As String
While client.Connected
Try
recv = client.Receive(data)
strData = Encoding.[UTF8].GetString(data, 0, recv)
listData.Items.Add("รับ: " & strData)
' MessageBox.Show(ex.Message);
Catch
End Try
End While
End Sub
Private Sub SendData(ByVal iar As IAsyncResult)
Try
Dim remote As Socket = DirectCast(iar.AsyncState, Socket)
Dim sent As Integer = remote.EndSend(iar)
Catch ex As SocketException
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btStart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btStart.Click
Try
newsock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ipep As New IPEndPoint(IPAddress.Parse(txtIP.Text), Integer.Parse(txtPort.Text))
newsock.Bind(ipep)
newsock.Listen(10)
newsock.BeginAccept(New AsyncCallback(AddressOf AcceptConn), newsock)
listdata.Items.Add("Server Started")
Catch ex As Exception
MessageBox.Show("IP หรือ Port ไม่ถุกต้อง" & ex.Message)
End Try
End Sub
Private Sub btStop_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
newsock.Shutdown(SocketShutdown.Both)
newsock.Close()
Catch
btStart.Enabled = True
End Try
End Sub
Private Sub btSend_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btsend.Click
If txtInput IsNot Nothing Then
Dim data As Byte() = Encoding.UTF8.GetBytes(txtInput.Text)
client.BeginSend(data, 0, data.Length, 0, New AsyncCallback(AddressOf SendData), client)
End If
End Sub
End Class