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;
- namespace jM2
- {
- class Client
- {
- public Socket clientSocket;
- public string clientIP;
- private byte[] clientBuffer = new byte[1024];
- /// <summary>
- /// Client constructor
- /// </summary>
- /// <param name="connectionSocket"></param>
- public Client(Socket connectionSocket)
- {
- clientSocket = connectionSocket;
- clientIP = connectionSocket.RemoteEndPoint.ToString();
- clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
- }
- /// <summary>
- /// Close client socket
- /// </summary>
- public void Disconnect()
- {
- try
- {
- Server.freeConnection(this);
- clientSocket.Close();
- }
- catch
- {
- }
- }
- /// <summary>
- /// Data arrived on client socket
- /// </summary>
- /// <param name="iar"></param>
- private void dataArrival(IAsyncResult iar)
- {
- try
- {
- int bytesReceived = clientSocket.EndReceive(iar);
- if (bytesReceived > 0)
- {
- Console.WriteLine("[" + clientIP + "](" + bytesReceived.ToString() + "): " + BitConverter.ToString(clientBuffer, 0, bytesReceived));
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("[" + ex.HelpLink + "]: " + ex.Message);
- Console.ReadLine();
- }
- clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
- }
- /// <summary>
- /// Send some data to client
- /// </summary>
- /// <param name="data"></param>
- public void Send(byte[] data)
- {
- clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(dataSent), null);
- }
- /// <summary>
- /// Executed when data has been sent to client
- /// </summary>
- /// <param name="iar"></param>
- private void dataSent(IAsyncResult iar)
- {
- clientSocket.EndSend(iar);
- }
- /// <summary>
- /// Convert string to byte array
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public byte[] stringToByteArray(string str)
- {
- System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
- return encoding.GetBytes(str);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment