Register for your free account! | Forgot your password?

Go Back   elitepvpers > MMORPGs > Conquer Online 2 > CO2 Programming
You last visited: Today at 18:31

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



My Socket Wrapper With Multi Threading and Events Similar to Classic Winsock

Discussion on My Socket Wrapper With Multi Threading and Events Similar to Classic Winsock within the CO2 Programming forum part of the Conquer Online 2 category.

Reply
 
Old   #1
 
elite*gold: 0
Join Date: Jan 2007
Posts: 118
Received Thanks: 20
My Socket Wrapper With Multi Threading and Events Similar to Classic Winsock

Hi guys to those who are planning to make their own proxy and want to have a socket wrapper which is similar to classic winsock then this class below is the one you are looking.

I created a multi threading socket of System.Net.Sockets. I also created the events similar to classic winsock such as OnConnectionRequest, OnDisconnection, OnConnect, OnDataArrival, OnSendComplete and OnError.


Code:
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.Threading
Public Class mysocket
    Private _listener As Socket
    Private listenThread As Thread

    Private client As Socket
    Private readThread As Thread
    Private connectThread As Thread
    Private sendThread As Thread

    Private _localport As Integer
    Private _remoteport As Integer
    Private _remoteIP As String


    Private data() As Byte
    Private Const ByteSize As Integer = 1024
    Private _Status As Integer
    Public ReadOnly Property Status()
        Get
            Return _Status
        End Get
    End Property
    Public Event OnConnectionRequest(ByVal client As Socket)
    Public Event OnDisconnection()
    Public Event OnConnect()
    Public Event OnDataArrival(ByVal bytesize As Integer)
    Public Event OnSendComplete(ByVal bytessent As Integer)
    Public Event OnError(ByVal errmsg As String)


    Public Sub New()
        ReDim data(ByteSize - 1)
        _Status = 0
    End Sub
    Public Property LocalPort() As Integer
        Get
            Return Me._localport
        End Get
        Set(ByVal value As Integer)
            Me._localport = value
        End Set
    End Property
    Public Property RemotePort() As Integer
        Get
            Return Me._remoteport
        End Get
        Set(ByVal value As Integer)
            Me._remoteport = value
        End Set
    End Property
    Public Property RemoteIP() As String
        Get
            Return Me._remoteIP
        End Get
        Set(ByVal value As String)
            Me._remoteIP = value
        End Set
    End Property


    Public Sub Listen()
        Try
            _listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim IEP As IPEndPoint = New IPEndPoint(IPAddress.Any, Me._localport)
            _listener.Bind(IEP)
            _listener.Listen(100)
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
        _listener.BeginAccept(New AsyncCallback(AddressOf WaitConnections), _listener)

        listenThread = New Thread(AddressOf WaitConnections)
        listenThread.IsBackground = True
        listenThread.Start()

    End Sub
    Private Sub WaitConnections(ByVal iar As IAsyncResult)
        Try
            Dim tmpsoc As Socket = DirectCast(iar.AsyncState, Socket)
            Dim mclient As Socket = tmpsoc.EndAccept(iar)
            RaiseEvent OnConnectionRequest(mclient)
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
            Try
                Me._listener.BeginAccept(New AsyncCallback(AddressOf WaitConnections), _listener)
                Return
            Catch ex1 As Exception
                RaiseEvent OnError(ex1.ToString)
            End Try
        End Try
        Try
            Me._listener.BeginAccept(New AsyncCallback(AddressOf WaitConnections), _listener)
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub

    Public Sub Accept(ByVal newclient As Socket)
        Try
            Me.client = newclient
            Me.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), Me.client)
            readThread = New Thread(AddressOf ReceiveData)
            readThread.IsBackground = True
            readThread.Start()
            _Status = 1   ' Connected
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub

    Private Sub ReceiveData(ByVal iar As IAsyncResult)
        Try
            Try
                Me.client = DirectCast(iar.AsyncState, Socket)
                Dim SE As SocketError = New SocketError
                If Me.client.Connected Then
                    Dim datalen As Integer = Me.client.EndReceive(iar, SE)
                    If SE = SocketError.Success And datalen <> 0 Then
                        RaiseEvent OnDataArrival(datalen)
                        Me.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), Me.client)
                    Else
                        _Status = 0  ' Disconnected
                        RaiseEvent OnDisconnection()
                    End If
                Else
                    _Status = 0  ' Disconnected
                    RaiseEvent OnDisconnection()
                End If
            Catch ex As Exception
                RaiseEvent OnError(ex.ToString)
            End Try
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub
    Public Sub GetData(ByRef buffer() As Byte, ByVal bytestotal As Integer)
        ReDim buffer(bytestotal - 1)
        System.Buffer.BlockCopy(Me.data, 0, buffer, 0, bytestotal)
    End Sub

    '' Client
    Public Sub Connect()
        Me.client = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim iep As New IPEndPoint(IPAddress.Parse(Me._remoteIP), Me._remoteport)
        client.BeginConnect(iep, New AsyncCallback(AddressOf Connected), client)

        connectThread = New Thread(AddressOf Connected)
        connectThread.IsBackground = True
        connectThread.Start()

    End Sub

    Private Sub Connected(ByVal iar As IAsyncResult)
        Try
            Me.client = DirectCast(iar.AsyncState, Socket)
            Me.client.EndConnect(iar)
            client.BeginReceive(data, 0, ByteSize, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), client)

            _Status = 1  ' Connected

            RaiseEvent OnConnect()
            readThread = New Thread(AddressOf ReceiveData)
            readThread.IsBackground = True
            readThread.Start()

        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub

    Public Sub SendData(ByVal buffer() As Byte)
        Try
            If client.Connected Then
                Me.client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf SendComplete), Me.client)
                sendThread = New Thread(AddressOf SendComplete)
                sendThread.IsBackground = True
                sendThread.Start()
            Else
            End If
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub
    Private Sub SendComplete(ByVal iar As IAsyncResult)
        Dim sent As Integer = 0
        Try
            Dim remote As Socket = DirectCast(iar.AsyncState, Socket)
            sent = remote.EndSend(iar)
            RaiseEvent OnSendComplete(sent)
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub
    Public Sub Close()
        Try
            Me.client.Close()
            RaiseEvent OnDisconnection()
            _Status = 0  ' Disconnected
            Try
                listenThread.Abort()
                readThread.Abort()
                connectThread.Abort()
                sendThread.Abort()

            Catch ex As Exception
                RaiseEvent OnError(ex.ToString)
            End Try
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub
    Public Sub StopListen()
        Try
            Me._listener.Close()
            RaiseEvent OnDisconnection()
            _Status = 0  ' Disconnected
            Try
                listenThread.Abort()
            Catch ex As Exception
                RaiseEvent OnError(ex.ToString)
            End Try
        Catch ex As Exception
            RaiseEvent OnError(ex.ToString)
        End Try
    End Sub
End Class

Implementation: I am using a simple client server application using the mysocket class.

Code:
Imports System.Text
Public Class Form1
    Private WithEvents myserver As mysocket = New mysocket
    Private WithEvents myclient As mysocket = New mysocket
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        myserver.LocalPort = 43001
        myserver.Listen()
    End Sub

    Private Sub OnConnectionRequest(ByVal client As System.Net.Sockets.Socket) Handles myserver.OnConnectionRequest
        myclient.Accept(client)
    End Sub


    Private Sub OnDataArrival(ByVal bytesize As Integer) Handles myclient.OnDataArrival
        Dim buffer() As Byte = {}
        myclient.GetData(buffer, bytesize)
        MsgBox("From client=>" & Encoding.ASCII.GetString(buffer))
    End Sub
    Private Sub OnDisconnect() Handles myclient.OnDisconnection
        MsgBox("client was disconnected !!!")
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If myclient.Status = 1 Then
            myclient.SendData(Encoding.ASCII.GetBytes(Me.TextBox1.Text))
        End If
    End Sub

    Private Sub SendCompete(ByVal bytessent As Integer) Handles myclient.OnSendComplete
        MsgBox("Send complete from server=> " & bytessent)
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        myclient.Close()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        myserver.StopListen()
    End Sub
End Class
xmen01235 is offline  
Thanks
2 Users
Old 10/19/2010, 20:21   #2
 
elite*gold: 21
Join Date: Jul 2005
Posts: 9,193
Received Thanks: 5,380
I don't have time to run through this fully atm but what language is this for? Looks like python if memory serves correctly but I never did anything in the least way advanced with python so wouldn't know...


Regardless, I'll assume it all works and therefor support it fully in that it's SOMETHING other than C# to provide an example to those looking to learn.
pro4never is offline  
Old 10/19/2010, 22:25   #3
 
elite*gold: 0
Join Date: Jun 2009
Posts: 787
Received Thanks: 314
vb.net
_tao4229_ is offline  
Old 10/20/2010, 02:32   #4
 
elite*gold: 0
Join Date: Jan 2007
Posts: 118
Received Thanks: 20
Quote:
Originally Posted by pro4never View Post
I don't have time to run through this fully atm but what language is this for? Looks like python if memory serves correctly but I never did anything in the least way advanced with python so wouldn't know...


Regardless, I'll assume it all works and therefor support it fully in that it's SOMETHING other than C# to provide an example to those looking to learn.
This is VB.net bro and this is the socket class that I am using on my proxy right now.
xmen01235 is offline  
Old 10/20/2010, 04:25   #5
 
elite*gold: 21
Join Date: Jul 2005
Posts: 9,193
Received Thanks: 5,380
Ahhh no wonder I was confused. Kept seeing minor things that looked python'esque and then seeing C# type stuff so I was rather 'wtf'd'.

Never seen VB code so yahhh.


Nice work ^^
pro4never is offline  
Old 10/20/2010, 16:51   #6
 
tkblackbelt's Avatar
 
elite*gold: 0
Join Date: Sep 2010
Posts: 291
Received Thanks: 95
Awsome work when I come back to my proxy project I'll probably convert that to c#
tkblackbelt is offline  
Old 10/22/2010, 23:12   #7
 
gabrola's Avatar
 
elite*gold: 0
Join Date: Dec 2006
Posts: 1,039
Received Thanks: 1,335
C# Version:
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
public class mysocket
{
	private Socket _listener;

	private Thread listenThread;
	private Socket client;
	private Thread readThread;
	private Thread connectThread;

	private Thread sendThread;
	private int _localport;
	private int _remoteport;

	private string _remoteIP;

	private byte[] data;
	private const int ByteSize = 1024;
	private int _Status;
	public object Status {
		get { return _Status; }
	}
	public event OnConnectionRequestEventHandler OnConnectionRequest;
	public delegate void OnConnectionRequestEventHandler(Socket client);
	public event OnDisconnectionEventHandler OnDisconnection;
	public delegate void OnDisconnectionEventHandler();
	public event OnConnectEventHandler OnConnect;
	public delegate void OnConnectEventHandler();
	public event OnDataArrivalEventHandler OnDataArrival;
	public delegate void OnDataArrivalEventHandler(int bytesize);
	public event OnSendCompleteEventHandler OnSendComplete;
	public delegate void OnSendCompleteEventHandler(int bytessent);
	public event OnErrorEventHandler OnError;
	public delegate void OnErrorEventHandler(string errmsg);


	public mysocket()
	{
		data = new byte[ByteSize];
		_Status = 0;
	}
	public int LocalPort {
		get { return this._localport; }
		set { this._localport = value; }
	}
	public int RemotePort {
		get { return this._remoteport; }
		set { this._remoteport = value; }
	}
	public string RemoteIP {
		get { return this._remoteIP; }
		set { this._remoteIP = value; }
	}


	public void Listen()
	{
		try {
			_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint IEP = new IPEndPoint(IPAddress.Any, this._localport);
			_listener.Bind(IEP);
			_listener.Listen(100);
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
		_listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);

		listenThread = new Thread(WaitConnections);
		listenThread.IsBackground = true;
		listenThread.Start();

	}
	private void WaitConnections(IAsyncResult iar)
	{
		try {
			Socket tmpsoc = (Socket)iar.AsyncState;
			Socket mclient = tmpsoc.EndAccept(iar);
			if (OnConnectionRequest != null) {
				OnConnectionRequest(mclient);
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
			try {
				this._listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);
				return;
			} catch (Exception ex1) {
				if (OnError != null) {
					OnError(ex1.ToString());
				}
			}
		}
		try {
			this._listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	public void Accept(Socket newclient)
	{
		try {
			this.client = newclient;
			this.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), this.client);
			readThread = new Thread(ReceiveData);
			readThread.IsBackground = true;
			readThread.Start();
			_Status = 1;
			// Connected
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	private void ReceiveData(IAsyncResult iar)
	{
		try {
			try {
				this.client = (Socket)iar.AsyncState;
				SocketError SE = new SocketError();
				if (this.client.Connected) {
					int datalen = this.client.EndReceive(iar, out SE);
					if (SE == SocketError.Success & datalen != 0) {
						if (OnDataArrival != null) {
							OnDataArrival(datalen);
						}
						this.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), this.client);
					} else {
						_Status = 0;
						// Disconnected
						if (OnDisconnection != null) {
							OnDisconnection();
						}
					}
				} else {
					_Status = 0;
					// Disconnected
					if (OnDisconnection != null) {
						OnDisconnection();
					}
				}
			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void GetData(ref byte[] buffer, int bytestotal)
	{
		buffer = new byte[bytestotal];
		System.Buffer.BlockCopy(this.data, 0, buffer, 0, bytestotal);
	}

	//' Client
	public void Connect()
	{
		this.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint iep = new IPEndPoint(IPAddress.Parse(this._remoteIP), this._remoteport);
		client.BeginConnect(iep, new AsyncCallback(Connected), client);

		connectThread = new Thread(Connected);
		connectThread.IsBackground = true;
		connectThread.Start();

	}

	private void Connected(IAsyncResult iar)
	{
		try {
			this.client = (Socket)iar.AsyncState;
			this.client.EndConnect(iar);
			client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), client);

			_Status = 1;
			// Connected

			if (OnConnect != null) {
				OnConnect();
			}
			readThread = new Thread(ReceiveData);
			readThread.IsBackground = true;
			readThread.Start();

		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	public void SendData(byte[] buffer)
	{
		try {
			if (client.Connected) {
				this.client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendComplete), this.client);
				sendThread = new Thread(SendComplete);
				sendThread.IsBackground = true;
				sendThread.Start();
			} else {
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	private void SendComplete(IAsyncResult iar)
	{
		int sent = 0;
		try {
			Socket remote = (Socket)iar.AsyncState;
			sent = remote.EndSend(iar);
			if (OnSendComplete != null) {
				OnSendComplete(sent);
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void Close()
	{
		try {
			this.client.Close();
			if (OnDisconnection != null) {
				OnDisconnection();
			}
			_Status = 0;
			// Disconnected
			try {
				listenThread.Abort();
				readThread.Abort();
				connectThread.Abort();
				sendThread.Abort();

			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void StopListen()
	{
		try {
			this._listener.Close();
			if (OnDisconnection != null) {
				OnDisconnection();
			}
			_Status = 0;
			// Disconnected
			try {
				listenThread.Abort();
			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
}
Implementation:
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
public class Form1
{
	private mysocket withEventsField_myserver = new mysocket();
	private mysocket myserver {
		get { return withEventsField_myserver; }
		set {
			if (withEventsField_myserver != null) {
				withEventsField_myserver.OnConnectionRequest -= OnConnectionRequest;
			}
			withEventsField_myserver = value;
			if (withEventsField_myserver != null) {
				withEventsField_myserver.OnConnectionRequest += OnConnectionRequest;
			}
		}
	}
	private mysocket withEventsField_myclient = new mysocket();
	private mysocket myclient {
		get { return withEventsField_myclient; }
		set {
			if (withEventsField_myclient != null) {
				withEventsField_myclient.OnDataArrival -= OnDataArrival;
				withEventsField_myclient.OnDisconnection -= OnDisconnect;
				withEventsField_myclient.OnSendComplete -= SendCompete;
			}
			withEventsField_myclient = value;
			if (withEventsField_myclient != null) {
				withEventsField_myclient.OnDataArrival += OnDataArrival;
				withEventsField_myclient.OnDisconnection += OnDisconnect;
				withEventsField_myclient.OnSendComplete += SendCompete;
			}
		}
	}
	private void Button1_Click(System.Object sender, System.EventArgs e)
	{
		myserver.LocalPort = 43001;
		myserver.Listen();
	}

	private void OnConnectionRequest(System.Net.Sockets.Socket client)
	{
		myclient.Accept(client);
	}


	private void OnDataArrival(int bytesize)
	{
		byte[] buffer = {
			
		};
		myclient.GetData(buffer, bytesize);
		Interaction.MsgBox("From client=>" + Encoding.ASCII.GetString(buffer));
	}
	private void OnDisconnect()
	{
		Interaction.MsgBox("client was disconnected !!!");
	}

	private void Button2_Click(System.Object sender, System.EventArgs e)
	{
		if (myclient.Status == 1) {
			myclient.SendData(Encoding.ASCII.GetBytes(this.TextBox1.Text));
		}
	}

	private void SendCompete(int bytessent)
	{
		Interaction.MsgBox("Send complete from server=> " + bytessent);
	}

	private void Button3_Click(System.Object sender, System.EventArgs e)
	{
		myclient.Close();
	}

	private void Button4_Click(System.Object sender, System.EventArgs e)
	{
		myserver.StopListen();
	}
}
May have some conversion errors.
gabrola is offline  
Thanks
1 User
Old 10/24/2010, 15:42   #8
 
elite*gold: 0
Join Date: Oct 2010
Posts: 1
Received Thanks: 0
code is great but i'm looking for somthing like this.

i cant public this class withevents as array,
eg.
Quote:
public withevents server() as mysocket
but it doesn't matter. because i still doesn't have variable like INDEX to control sockets.
i want variable like INDEX to controll sockets.

Quote:
Private Sub OnDataArrival(ByVAL INDEX as integer, ByVal bytesize As Integer) Handles myclient.OnDataArrival

End Sub
i'll be pleased if you help me
mr.xakerx is offline  
Old 10/25/2010, 05:25   #9
 
elite*gold: 0
Join Date: Jan 2007
Posts: 118
Received Thanks: 20
Quote:
Originally Posted by gabrola View Post
C# Version:
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
public class mysocket
{
	private Socket _listener;

	private Thread listenThread;
	private Socket client;
	private Thread readThread;
	private Thread connectThread;

	private Thread sendThread;
	private int _localport;
	private int _remoteport;

	private string _remoteIP;

	private byte[] data;
	private const int ByteSize = 1024;
	private int _Status;
	public object Status {
		get { return _Status; }
	}
	public event OnConnectionRequestEventHandler OnConnectionRequest;
	public delegate void OnConnectionRequestEventHandler(Socket client);
	public event OnDisconnectionEventHandler OnDisconnection;
	public delegate void OnDisconnectionEventHandler();
	public event OnConnectEventHandler OnConnect;
	public delegate void OnConnectEventHandler();
	public event OnDataArrivalEventHandler OnDataArrival;
	public delegate void OnDataArrivalEventHandler(int bytesize);
	public event OnSendCompleteEventHandler OnSendComplete;
	public delegate void OnSendCompleteEventHandler(int bytessent);
	public event OnErrorEventHandler OnError;
	public delegate void OnErrorEventHandler(string errmsg);


	public mysocket()
	{
		data = new byte[ByteSize];
		_Status = 0;
	}
	public int LocalPort {
		get { return this._localport; }
		set { this._localport = value; }
	}
	public int RemotePort {
		get { return this._remoteport; }
		set { this._remoteport = value; }
	}
	public string RemoteIP {
		get { return this._remoteIP; }
		set { this._remoteIP = value; }
	}


	public void Listen()
	{
		try {
			_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint IEP = new IPEndPoint(IPAddress.Any, this._localport);
			_listener.Bind(IEP);
			_listener.Listen(100);
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
		_listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);

		listenThread = new Thread(WaitConnections);
		listenThread.IsBackground = true;
		listenThread.Start();

	}
	private void WaitConnections(IAsyncResult iar)
	{
		try {
			Socket tmpsoc = (Socket)iar.AsyncState;
			Socket mclient = tmpsoc.EndAccept(iar);
			if (OnConnectionRequest != null) {
				OnConnectionRequest(mclient);
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
			try {
				this._listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);
				return;
			} catch (Exception ex1) {
				if (OnError != null) {
					OnError(ex1.ToString());
				}
			}
		}
		try {
			this._listener.BeginAccept(new AsyncCallback(WaitConnections), _listener);
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	public void Accept(Socket newclient)
	{
		try {
			this.client = newclient;
			this.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), this.client);
			readThread = new Thread(ReceiveData);
			readThread.IsBackground = true;
			readThread.Start();
			_Status = 1;
			// Connected
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	private void ReceiveData(IAsyncResult iar)
	{
		try {
			try {
				this.client = (Socket)iar.AsyncState;
				SocketError SE = new SocketError();
				if (this.client.Connected) {
					int datalen = this.client.EndReceive(iar, out SE);
					if (SE == SocketError.Success & datalen != 0) {
						if (OnDataArrival != null) {
							OnDataArrival(datalen);
						}
						this.client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), this.client);
					} else {
						_Status = 0;
						// Disconnected
						if (OnDisconnection != null) {
							OnDisconnection();
						}
					}
				} else {
					_Status = 0;
					// Disconnected
					if (OnDisconnection != null) {
						OnDisconnection();
					}
				}
			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void GetData(ref byte[] buffer, int bytestotal)
	{
		buffer = new byte[bytestotal];
		System.Buffer.BlockCopy(this.data, 0, buffer, 0, bytestotal);
	}

	//' Client
	public void Connect()
	{
		this.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint iep = new IPEndPoint(IPAddress.Parse(this._remoteIP), this._remoteport);
		client.BeginConnect(iep, new AsyncCallback(Connected), client);

		connectThread = new Thread(Connected);
		connectThread.IsBackground = true;
		connectThread.Start();

	}

	private void Connected(IAsyncResult iar)
	{
		try {
			this.client = (Socket)iar.AsyncState;
			this.client.EndConnect(iar);
			client.BeginReceive(data, 0, ByteSize, SocketFlags.None, new AsyncCallback(ReceiveData), client);

			_Status = 1;
			// Connected

			if (OnConnect != null) {
				OnConnect();
			}
			readThread = new Thread(ReceiveData);
			readThread.IsBackground = true;
			readThread.Start();

		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}

	public void SendData(byte[] buffer)
	{
		try {
			if (client.Connected) {
				this.client.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendComplete), this.client);
				sendThread = new Thread(SendComplete);
				sendThread.IsBackground = true;
				sendThread.Start();
			} else {
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	private void SendComplete(IAsyncResult iar)
	{
		int sent = 0;
		try {
			Socket remote = (Socket)iar.AsyncState;
			sent = remote.EndSend(iar);
			if (OnSendComplete != null) {
				OnSendComplete(sent);
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void Close()
	{
		try {
			this.client.Close();
			if (OnDisconnection != null) {
				OnDisconnection();
			}
			_Status = 0;
			// Disconnected
			try {
				listenThread.Abort();
				readThread.Abort();
				connectThread.Abort();
				sendThread.Abort();

			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
	public void StopListen()
	{
		try {
			this._listener.Close();
			if (OnDisconnection != null) {
				OnDisconnection();
			}
			_Status = 0;
			// Disconnected
			try {
				listenThread.Abort();
			} catch (Exception ex) {
				if (OnError != null) {
					OnError(ex.ToString());
				}
			}
		} catch (Exception ex) {
			if (OnError != null) {
				OnError(ex.ToString());
			}
		}
	}
}
Implementation:
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
public class Form1
{
	private mysocket withEventsField_myserver = new mysocket();
	private mysocket myserver {
		get { return withEventsField_myserver; }
		set {
			if (withEventsField_myserver != null) {
				withEventsField_myserver.OnConnectionRequest -= OnConnectionRequest;
			}
			withEventsField_myserver = value;
			if (withEventsField_myserver != null) {
				withEventsField_myserver.OnConnectionRequest += OnConnectionRequest;
			}
		}
	}
	private mysocket withEventsField_myclient = new mysocket();
	private mysocket myclient {
		get { return withEventsField_myclient; }
		set {
			if (withEventsField_myclient != null) {
				withEventsField_myclient.OnDataArrival -= OnDataArrival;
				withEventsField_myclient.OnDisconnection -= OnDisconnect;
				withEventsField_myclient.OnSendComplete -= SendCompete;
			}
			withEventsField_myclient = value;
			if (withEventsField_myclient != null) {
				withEventsField_myclient.OnDataArrival += OnDataArrival;
				withEventsField_myclient.OnDisconnection += OnDisconnect;
				withEventsField_myclient.OnSendComplete += SendCompete;
			}
		}
	}
	private void Button1_Click(System.Object sender, System.EventArgs e)
	{
		myserver.LocalPort = 43001;
		myserver.Listen();
	}

	private void OnConnectionRequest(System.Net.Sockets.Socket client)
	{
		myclient.Accept(client);
	}


	private void OnDataArrival(int bytesize)
	{
		byte[] buffer = {
			
		};
		myclient.GetData(buffer, bytesize);
		Interaction.MsgBox("From client=>" + Encoding.ASCII.GetString(buffer));
	}
	private void OnDisconnect()
	{
		Interaction.MsgBox("client was disconnected !!!");
	}

	private void Button2_Click(System.Object sender, System.EventArgs e)
	{
		if (myclient.Status == 1) {
			myclient.SendData(Encoding.ASCII.GetBytes(this.TextBox1.Text));
		}
	}

	private void SendCompete(int bytessent)
	{
		Interaction.MsgBox("Send complete from server=> " + bytessent);
	}

	private void Button3_Click(System.Object sender, System.EventArgs e)
	{
		myclient.Close();
	}

	private void Button4_Click(System.Object sender, System.EventArgs e)
	{
		myserver.StopListen();
	}
}
May have some conversion errors.
Thanks for the conversion bro ...
xmen01235 is offline  
Old 10/25/2010, 05:52   #10
 
elite*gold: 0
Join Date: Jan 2007
Posts: 118
Received Thanks: 20
Quote:
Originally Posted by mr.xakerx View Post
code is great but i'm looking for somthing like this.

i cant public this class withevents as array,
eg.


but it doesn't matter. because i still doesn't have variable like INDEX to control sockets.
i want variable like INDEX to controll sockets.



i'll be pleased if you help me
You don't need to declare such array bro instead use the List() class, just a take a look on how I manage my multi connection client -server application below:
Code:
Imports System.Text
Imports System.Array
Imports System.Net.Sockets


Module modTCP
    Public ListeningPort As Integer                     ' The port where proxy will listen the incoming connection from client(Conquer)
    Public LoginServerIP As String                      ' The login server IP

    Dim WithEvents ListenerSoc As As mysocket = New mysocket
    Dim Clients As List(Of ClientConnection)

    Public Sub StartListen()
        ListenerSoc.LocalPort = ListeningPort
        ListenerSoc.Listen()
        LogEvents("Waiting for connection at port " & ListeningPort)
    End Sub

    Private Sub OnConnectionReq(ByVal _tcpclient As Socket) Handles ListenerSoc.OnConnectionRequest

	LogEvents("Client => " & _tcpclient.ToString & " is requesting for connection", Now.ToString)
        Dim fromClientSoc As mysocket = New mysocket
        Dim connClient As New ClientConnection(fromClientSoc, _tcpclient)
        AddHandler connClient.AuthenticationConnClose, AddressOf OnAuthenticationClose
        ' You can add more event here for client connection class

        Clients.Add(connClient)
    End Sub

    Private Sub OnAuthenticationClose(ByVal cclient As clsAuthConnection)
        LogEvents("Class Container for authentication connection " & cclient.SocConnection.ToString & " has been removed", Now.ToString)
        Clients.Remove(cclient)
    End Sub

    Public Sub LogEvents(ByVal msg As String, ByVal _time As String)
        frmMain.mLogEvents(msg, _time)
    End Sub
End Module

Class ClientConnection
    Public listofLogs As New List(Of log)
    Public WithEvents ClientProxySoc As As mysocket = New mysocket
    Public Event AuthenticationConnClose(ByVal cclient As clsAuthConnection)

    Public Sub New(ByVal client As mysocket, ByVal _tcpclient As Socket)
        ClientProxySoc = client
        ClientProxySoc.Accept(_tcpclient)

        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' For conquer proxy you can initialize here the authentication encryption
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''   

       
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' For conquer proxy you can add here the socket that will connect to the game server
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''   
    End Sub
    
    Private Sub OnClose_ClientProxySoc() Handles ClientProxySoc.OnDisconnection
        LogEvents("Connection close")
	RaiseEvent AuthenticationConnClose(Me)
    End Sub
    Private Sub ClientProxySoc_OnDataArrival(ByVal bytestotal As Integer) Handles ClientProxySoc.OnDataArrival
        Dim buffer() As Byte = {}
        ReDim buffer(bytestotal)

        ClientProxySoc.GetData(buffer, bytestotal)
        
	'AutCrypthCP.Encrypt(buffer)
        
	LogEvents("Client Packet: " & Encoding.ASCII.GetString(buffer))
        
	'CPacket = New packet.myPacket(buffer)
        'If packet.LoginInformation.IsThisType(CPacket) Then
        '    Dim logInfo As packet.LoginInformation = New packet.LoginInformation(CPacket)
        '    Me.ServerName = logInfo.ServerName
        '    Me.LoginAccountID = logInfo.LoginID
        'End If
        'AutCrypthCP.Decrypt(buffer)
        'Try
        '    Me.ProxyServerLoginSoc.SendData(buffer)
        'Catch ex As Exception
        '    Me.ProxyServerLoginSoc.Close()
        '    RaiseEvent AuthenticationConnClose(Me)
        'End Try

    End Sub

    Private Sub LogEvents(ByVal mevents As String)
        Dim mlog As log = New log
        mlog.msg = mevents
        Me.listofLogs.Add(mlog)
        mlog = Nothing
    End Sub

End Class

' Miscelaneous for logging purposes
Public Class log
    Private _msg As String
    Private _timecreated As String
    Public Property msg() As String
        Get
            Return _msg
        End Get
        Set(ByVal value As String)
            _timecreated = Now().ToString
            _msg = value
        End Set
    End Property
    Public ReadOnly Property TimeCreated() As String
        Get
            Return _timecreated
        End Get
    End Property
End Class
Please debug it with yourself if you want to try it. But the algorithm is there and thats how i manage my server with multiple client.
xmen01235 is offline  
Reply


Similar Threads Similar Threads
D2NT und Glide Wrapper
05/27/2014 - Diablo 2 - 6 Replies
Hi, folgendes Problem: Ich hab mir den Glide Wrapper für Diablo2 besorgt und installiert, funktioniert auch einwandfrei... Jedoch nicht mit d2nt... da d2nt standartmäßig Direct3D benutzt bzw. Direct Draw wenn "low quality" aktiviert ist. Meine Frage: Wie bekomm ich es hin, dass d2nt auch glide benutzt anstelle von D3D bzw. Direct Draw?! Danke für alle kommenden Lösungsvorschläge.
au3 wrapper
12/23/2008 - Guild Wars - 11 Replies
hi ganz dumme fragen^^ wo gibst den neuen au3 wrapper zum download bei google habe ich ncihts gefunden oder ich bin einfach zu blöd zum richtig googlen kann mir wer weiter helfen??
Empty wrapper help
01/18/2008 - WoW PServer Exploits, Hacks & Tools - 1 Replies
I play on wowfusion, the only wrapping paper i can get is the empty wrapper. But everytime i try to wrap something i get : Wrapped item can't be wrap. What can i do? I tryed a lot of item and i always get this same message. I tryed slot switching , other bags and ... Any help would be appreciated. Thx
Builder für ExE Wrapper Erstellen - wie geht man vor?
01/11/2008 - General Coding - 6 Replies
Hey! Ich habe angefangen einen Wrapper zu schreiben... das Programm zum entschlüsseln und dann ausführen der verpackten exe funkt.. - aber leider weiß ich nicht, wie ich sowas wie einen Builder baue. :confused: Deshalb wende ich mich nun an euch.. was ich nun gemacht hätte: ich hätte den compiler mitgeliefert und dann von dem builder code generieren lassen, der dann compiliert wird. Das ist aber vermutlich ziemlich noobig und je nach compiler auch rechtlich schwierig... ;) Meine Frage also -...
winsock in vb.net?
12/29/2007 - Conquer Online 2 - 4 Replies
anyone know how to get winsock into vb.net?ive been googleing for an answer and cant findone. i downloaded oswinsock and still not sure how to use it?? Ive been using vb6 for a while and am using vb 2005 for the first time and this is pissing me off.i read i should use systemcom.net or somthing? just anyone know how i can use winsock in vb.net or explain what i need to do,before i give up on this .net framework and stick with my trusty vb6 if anyone has a simple source proxy in...



All times are GMT +1. The time now is 18:34.


Powered by vBulletin®
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2026 elitepvpers All Rights Reserved.