05-20-2011, 02:49 AM
What's up support forums?!?!
I was bored and decided to make a little example of how EASY it is to use Sockets. This is my first vid so bear with me. It ran a little long but it covers both Server and Client. This demonstrates a single client connection. Depending on the feedback I receive I may release another demo that shows how to incorporate multiple clients.
What is this?
This is a demonstration on how to use Sockets when programming Server/Client applications. It can be used in chat programs, naughty black hat stuff, IRC clients etc.
Can I c/p you code?
Sure why not, it is up to you to learn from this. You get from this what you put in. So if you actually go through the code and understand it, you will learn far more than c/p'ing.
Enjoy. Keep SF alive by posting!
Video:
Server Code:
Code:
Imports System.Net, System.Net.Sockets
Public Class frmServer
Dim server As Socket
Dim client As Socket
Dim bytes As Byte() = New Byte(1023) {}
Private Sub frmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
server = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim xEndpoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 6969)
server.Bind(xEndpoint)
server.Listen(2)
server.BeginAccept(New AsyncCallback(AddressOf OnAccept), vbNull)
End Sub
Private Sub OnAccept(ByVal ar As IAsyncResult)
client = server.EndAccept(ar)
client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
End Sub
Private Sub OnRecieve(ByVal ar As IAsyncResult)
client = ar.AsyncState
client.EndReceive(ar)
client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
MessageBox.Show(message)
End Sub
End Class
Client Code:
Code:
Imports System.Net, System.Net.Sockets
Imports System.Text.ASCIIEncoding
Public Class frmClient
Dim client As Socket
Dim host As String = "127.0.0.1"
Dim port As Integer = "6969"
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
client = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim IP As IPAddress = IPAddress.Parse(host)
Dim xIpEndPoint As IPEndPoint = New IPEndPoint(IP, port)
client.BeginConnect(xIpEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing)
btnConnect.Enabled = False
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim bytes As Byte() = ASCII.GetBytes(txtMessage.Text)
client.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), client)
End Sub
Private Sub OnConnect(ByVal ar As IAsyncResult)
client.EndConnect(ar)
MessageBox.Show("Connected")
End Sub
Private Sub OnSend(ByVal ar As IAsyncResult)
client.EndSend(ar)
End Sub
End Class