Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- using System.Threading;
- namespace Socket
- {
- public class CustomSocket
- {
- //members
- //private
- private Socket m_Socket;
- private String m_IPAddress;
- private int m_Port;
- private bool m_Connected = false;
- private CustomBuffer m_buffer;
- public event EventHandler<FullMessageEventArgs> FullMessage;
- //constructor
- public CustomSocket(String IPAddress, int Port)
- {
- this.m_IPAddress = IPAddress;
- this.m_Port = Port;
- this.m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- this.m_buffer = new CustomBuffer(this);
- }
- //methods
- internal void onFullMessage(object sender, FullMessageEventArgs e)
- {
- if (e.Data != null)
- {
- FullMessage(sender, e);
- }
- }
- public bool Connect()
- {
- try
- {
- this.m_Socket.Connect(this.m_IPAddress, this.m_Port);
- new Thread(new ThreadStart(this.ListenThreadMethod)).Start();
- }
- catch (SocketException)
- {
- return false;
- }
- catch (ArgumentNullException)
- {
- return false;
- }
- catch (ObjectDisposedException)
- {
- return false;
- }
- catch (InvalidOperationException)
- {
- return false;
- }
- this.m_Connected = true;
- return true;
- }
- public void Disconnect()
- {
- try
- {
- this.m_Connected = false;
- this.m_Socket.Close();
- }
- catch { }
- }
- public bool Send(byte[] data)
- {
- try
- {
- int bytesSent = this.m_Socket.Send(data);
- return bytesSent == data.Length;
- }
- catch (SocketException)
- {
- return false;
- }
- catch (ArgumentNullException)
- {
- return false;
- }
- catch (ObjectDisposedException)
- {
- return false;
- }
- catch (InvalidOperationException)
- {
- return false;
- }
- }
- private void ListenThreadMethod()
- {
- byte[] recvBuffer = new byte[1024];
- int bytesReceived = 0;
- while (this.m_Connected)
- {
- try
- {
- bytesReceived = this.m_Socket.Receive(recvBuffer);
- if (bytesReceived == 0)
- {
- return;
- }
- byte[] data = new byte[bytesReceived];
- Array.Copy(recvBuffer, 0, data, 0, bytesReceived);
- if (data != null)
- {
- this.m_buffer.WriteBytes(data);
- }
- }
- catch (SocketException)
- {
- return;
- }
- catch (ArgumentNullException)
- {
- return;
- }
- catch (ObjectDisposedException)
- {
- return;
- }
- catch (InvalidOperationException)
- {
- return;
- }
- }
- }
- //get
- String IPAddress
- {
- get { return this.m_IPAddress; }
- }
- int Port
- {
- get { return this.m_Port; }
- }
- bool Connected
- {
- get { return this.m_Connected; }
- }
- }
- public class FullMessageEventArgs : EventArgs
- {
- public byte[] Data { get; set; }
- public FullMessageEventArgs(byte[] data)
- {
- this.Data = data;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement