Menu

[r40]: / trunk / WhatsappClient / WhatsAppProtocol / WhatsNetwork.cs  Maximize  Restore  History

Download this file

104 lines (91 with data), 2.8 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
public class WhatsNetwork
{
private readonly int recvTimeout;
private readonly string whatsHost;
private readonly int whatsPort;
private List<byte> incomplete_message = new List<byte>();
public Socket socket;
public WhatsNetwork(string whatsHost, int port, int timeout = 2000)
{
this.recvTimeout = timeout;
this.whatsHost = whatsHost;
this.whatsPort = port;
this.incomplete_message = new List<byte>();
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Connect()
{
this.socket.Connect(this.whatsHost, this.whatsPort);
this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, this.recvTimeout);
if (!this.socket.Connected)
throw new ConnectionException("Cannot connect");
}
public void Disconenct()
{
if (this.socket.Connected)
this.socket.Disconnect(true);
}
public byte[] ReadData()
{
List<byte> buff = new List<byte>();
byte[] ret = Socket_read(1024);
return ret;
}
public void SendData(string data)
{
Socket_send(data, data.Length, 0);
}
public void SendData(byte[] data)
{
Socket_send(data);
}
private byte[] Socket_read(int length)
{
if (!socket.Connected)
{
throw new ConnectionException();
}
var buff = new byte[length];
int receiveLength = 0;
do
{
try
{
receiveLength = socket.Receive(buff, 0, length, 0);
}
catch (SocketException excpt)
{
if (excpt.SocketErrorCode == SocketError.TimedOut)
{
return null;
}
else
{
System.Windows.Forms.MessageBox.Show(excpt.SocketErrorCode.ToString());
}
}
} while (receiveLength <= 0);
byte[] tmpRet = new byte[receiveLength];
if (receiveLength > 0)
Buffer.BlockCopy(buff, 0, tmpRet, 0, receiveLength);
return tmpRet;
}
private void Socket_send(string data, int length, int flags)
{
var tmpBytes = Encoding.UTF8.GetBytes(data);
this.socket.Send(tmpBytes);
}
private void Socket_send(byte[] data)
{
this.socket.Send(data);
}
public bool SocketStatus
{
get { return socket.Connected; }
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.