simcard message trans/receiver simulator - simulation

We have a project that we should send message to a huge number of sim cards (more than 1 Million) and receive and handle answers.
For testing this, I am using Selenium SMPPSim to simulate sending a message.
this is work fine for sending messages. and with enabling callback server I can receive messages that I send on another port.
But my question is how can I send back a message to SMPP server?
I am using EasySMPP library for connecting to smpp server
My SMPP Server Code:
private SMPPClient _client;
private readonly object _lockObject = new object();
public SMPPClient GetClient()
{
if (_client != null)
{
return _client;
}
lock (_lockObject)
{
_client = new SMPPClient();
var smsc = new SMSC
{
Host = "127.0.0.1",
Port = 2775,
SystemId = "smppclient1",
Password = "password",
SourceTon = 5,
SourceNpi = 1,
AddrTon = 1,
AddrNpi = 1,
SystemType = "8945",
};
_client.OnDeliverSm += Client_OnDeliverSm;
Console.WriteLine("Client_OnDeliverSm added");
_client.OnSubmitSmResp += Client_OnSubmitSmResp;
Console.WriteLine("OnSubmitSmResp added");
_client.AddSMSC(smsc);
if (!_client.Connect())
throw new Exception($"Can not connect to smpp link: {smsc.Host} : {smsc.Port}");
return _client;
}
}
public void SendByCampaignItemId()
{
var smppClient = GetClient();
lock (smppClient)
{
var msgId = smppClient.SubmitSM(1, 1, "339123456789", 1, 1, "339632587436",
0x40, // EsmClass.UdhIndicator
0x7f, // protocol identifier
0, // priority flag level 0
DateTime.MinValue,
DateTime.MinValue,
// DateTime.Now.AddMinutes(10),
//DateTime.Now.AddHours(3),
(byte)DeliveryReportType.AlwaysSendDeliveryReport,
0x00, //replace if present
0xf6, // data coding
0, // default msg id
new byte[] { 0x02,0x70,0x00,0x34,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF});
}
}
private void Client_OnSubmitSmResp(SubmitSmRespEventArgs e)
{
Console.WriteLine("Submit Received");
}
private void Client_OnDeliverSm(DeliverSmEventArgs e)
{
Console.WriteLine("Deliver Received");
}
And here is my code which listens to port 3333:
static void Main(string[] args)
{
TcpListener server = null;
try
{
Int32 port = 3333;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
//WHAT SHOULD I DO HERE SO THAT I CAN SEND BACK A MESSAGE (DELIVER SM) TO SMPP SIM??!!!
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
And my SMPPSIM Config file :
SMPP_PORT=2775
SMPP_CONNECTION_HANDLERS=10
CONNECTION_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardConnectionHandler
PROTOCOL_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardProtocolHandler
LIFE_CYCLE_MANAGER=com.seleniumsoftware.SMPPSim.LifeCycleManager
MESSAGE_STATE_CHECK_FREQUENCY=5000
MAX_TIME_ENROUTE=10000
DELAY_DELIVERY_RECEIPTS_BY=0
PERCENTAGE_THAT_TRANSITION=75
PERCENTAGE_DELIVERED=90
PERCENTAGE_UNDELIVERABLE=6
PERCENTAGE_ACCEPTED=2
PERCENTAGE_REJECTED=2
DISCARD_FROM_QUEUE_AFTER=60000
HTTP_PORT=88
HTTP_THREADS=1
DOCROOT=www
AUTHORISED_FILES=/css/style.css,/index.htm,/inject_mo.htm,/favicon.ico,/images/logo.gif,/images/dots.gif,/user-guide.htm,/images/homepage.gif,/images/inject_mo.gif
INJECT_MO_PAGE=/inject_mo.htm
SYSTEM_IDS=smppclient1,smppclient2
PASSWORDS=password,password
OUTBIND_ENABLED=false
OUTBIND_ESME_IP_ADDRESS=127.0.0.1
OUTBIND_ESME_PORT=2776
OUTBIND_ESME_SYSTEMID=smppclient1
OUTBIND_ESME_PASSWORD=password
DELIVERY_MESSAGES_PER_MINUTE=0
DELIVER_MESSAGES_FILE=deliver_messages.csv
LOOPBACK=TRUE
ESME_TO_ESME=false
OUTBOUND_QUEUE_MAX_SIZE=1000
INBOUND_QUEUE_MAX_SIZE=1000
DELAYED_INBOUND_QUEUE_PROCESSING_PERIOD=60
DELAYED_INBOUND_QUEUE_MAX_ATTEMPTS=100
DECODE_PDUS_IN_LOG=true
CAPTURE_SME_BINARY=false
CAPTURE_SME_BINARY_TO_FILE=sme_binary.capture
CAPTURE_SMPPSIM_BINARY=false
CAPTURE_SMPPSIM_BINARY_TO_FILE=smppsim_binary.capture
CAPTURE_SME_DECODED=false
CAPTURE_SME_DECODED_TO_FILE=sme_decoded.capture
CAPTURE_SMPPSIM_DECODED=false
CAPTURE_SMPPSIM_DECODED_TO_FILE=smppsim_decoded.capture
CALLBACK=true
CALLBACK_ID=SIM1
CALLBACK_TARGET_HOST=localhost
CALLBACK_PORT=3333
DELIVER_SM_INCLUDES_USSD_SERVICE_OP=false
DELIVERY_RECEIPT_OPTIONAL_PARAMS=true
DELIVERY_RECEIPT_TLV=1403/0A/34343132333435363738
SMSCID=SMPPSim
SIMULATE_VARIABLE_SUBMIT_SM_RESPONSE_TIMES=false
And another question:
If SMPPSim is not a good choice for my work, what else can i use?
UPDATE 1:
I look a little more and I think I find a simpler question.
assume that i have to SMPPSims.
How can I send message from a SMPPSim to another one?

Related

Can't read/write data (TcpClient/NetworkStream)

A former employees used TCP Client & TCP Listener, Thread, and NetworkStream to create a payment server with Unity 32-bit for Unity 32-bit games and payment connections.
(I don't know what I'm talking about either)
BUT Only the first payment is successful, and the second payment cannot be 'Read' even if it is 'Write'.
(Or maybe client server listener(?) is dumb.... ;( )
So I tried debugging, but this comment came up.
'SocketException System.Net.Sockets.SocketException: Blocking operation aborted by calling WSACanceBlockingCall.'
I can't even connect to the clientServer.
It's fatal to the company that only one payment is made.
This is because after the payment, the game proceeds and when the GameLife is exhausted, you have to return to the lobby and pay again.
But "Write" works, but why doesn't it go on after that?
If you are disconnected from the game and payment server, you will be warned that you are disconnected from the server.
I'm so confused. I'm a client developer and I don't understand anything because I think I'm developing a server.
I'm just a three-month-old junior developer...
This is my client Write Code
public void SendMessage()
{
if (socketConnection == null)
{
return;
}
try
{
// Get a stream object for writing.
NetworkStream stream = socketConnection.GetStream();
if (stream.CanWrite)
{
//string clientMessage = "This is a message from one of your clients.";
string clientMessage = string.Format("Charge,{0}",DataManager.instance.payData._Money);
// Convert string message to byte array.
//byte[] clientMessageAsByteArray = Encoding.ASCII.GetBytes(clientMessage);
byte[] clientMessageAsByteArray = Encoding.UTF8.GetBytes(clientMessage);
// Write byte array to socketConnection stream.
stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length);
Debug.Log("Client sent his message - should be received by server");
}
}
catch (SocketException socketException)
{
serverState = ServerState.Disconnect;
Debug.Log("Socket exception: " + socketException);
}
}
This is Server Read Code
private void ListenForIncomingRequests()
{
try
{
// Get Local IPv4 Address
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
address = ip.ToString();
}
}
Debug.Log("address : "+ address);
// Create listener on localhost port 8052.
tcpListener = new TcpListener(IPAddress.Parse(address), 50001);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
Debug.Log(connectedTcpClient.ToString());
// Get a stream object for reading
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
// Read incoming stream into byte arrary.
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incomingData = new byte[length];
Array.Copy(bytes, 0, incomingData, 0, length);
// Convert byte array to string message.
//string clientMessage = Encoding.ASCII.GetString(incomingData);
string[] message = Encoding.UTF8.GetString(incomingData).Split(',');
string clientMessage = message[0];
string value = message[1];
if (string.IsNullOrEmpty(_clientMessage))
{
_clientMessage = clientMessage;
if (_clientMessage.Equals("Charge"))
{
_clientMessage = string.Empty;
pay.PayEvent(int.Parse(value));
}
}
Debug.Log("client message received as: " + clientMessage);
Debug.Log("_client message received as: " + _clientMessage);
Debug.Log(length);
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}

Socket.BeginSendTo and Socket.BeginReceiveFrom is not sending or receiving the data

I am trying to make a dedicated server for my new game using UDP sockets. I am using Socket.BeginSendTo() and Socket.BeginReceiveFrom() methods in order to send my data.
I am receiving the callbacks from both the methods, but when I am trying to Encoding.ASCII.GetString(buffer) it is not showing me any strings. I am not sure if there is a problem while sending, or if there is a problem while receiving.
I know that UDP does not guarantee the transmission, that's why I tried to send my data more then twice more like 10 times. Each time, I receive a callback that the data is sent on the client side and the data is received on the server side. But, as I said, when I am trying to read the data using Encoding, it shows nothing. I tried to do a string null or empty check while receiving the data. It said that the string is not empty, but when I try to Console.WriteLine(), it showed nothing in the console.
Here is the client code, where I am sending the data to the server:
public void SendMessage(Activity activityCode, String inputedString) //I am changed this
{
byte[] data = readMessage.WriteData(activityCode, inputedString);
if(data != null)
{
Debug.Log(data.Length); //this returned 11
clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
}
Array.Clear(readMessage.data, 0, readMessage.data.Length);
}
private void OnSend(IAsyncResult ar)
{
Debug.Log("sent"); //I am getting this callback in my console
}
Here is my server code, where I am receiving the data:
private void StartReceiveingData()
{
try
{
if (!serverSocket.IsBound)
{
serverSocket.Bind(localServerIPEndPoint);
}
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
//The epSender identifies the incoming clients
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void OnReceive(IAsyncResult ar)
{
StaticTest.printDData();
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.EndReceiveFrom(ar, ref epSender);
StartReceiveingData();
}
And here is where I am reading the data:
static public class StaticTest
{
static public byte[] byteData = new byte[1024];
public static void printDData()
{
Console.WriteLine("Reding the received data" + Encoding.UTF8.GetString(byteData));
}
}
UPDATE: I tried this code, but it still does not work:
private void StartReceiveingData()
{
try
{
if (!serverSocket.IsBound)
{
serverSocket.Bind(localServerIPEndPoint);
}
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
//The epSender identifies the incoming clients
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void OnReceive(IAsyncResult ar)
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
int numData = serverSocket.EndReceiveFrom(ar, ref epSender);
if (!clientList.ContainsKey(epSender))
{
Client client = new Client(epSender);
clientList.Add(epSender, client);
}
if(clientList.TryGetValue(epSender, out Client client1))
{
string _receivedData = Encoding.UTF8.GetString(byteData, 0, numData);
Console.WriteLine(_receivedData + " Data that came");
//client1.RecieveDataFromMyGameObject(_receivedData);
}
StartReceiveingData();
}
And here is where I am reading the data:
public string TakeActions(string _recivedData)
{
int activityInput = Convert.ToInt32(_recivedData.Substring(0,1)); //there is an error
ActivityRequest activity = (ActivityRequest)activityInput;
Console.WriteLine("Current activity Number : " + activity);
if(activity == ActivityRequest.SetupClient)
{
SetupClientDataActivity.setupClientData(client,_recivedData.Substring(1,_recivedData.Length-1));
}
else if(activity == ActivityRequest.MatchMaking)
{
Console.WriteLine("Asking Room manager to get into a room");
// roomManager.AddAClientToARoom(client);
}
return null;
}
Your OnSend callback needs to call Socket.EndSendTo() to finish the send operation and tell you whether the operation was successful or not.
Your OnReceive callback is calling Socket.EndReceiveFrom(), but you are ignoring its result, and you are trying to print the byteData before calling EndReceiveFrom() to finish the read operation and tell you how many bytes were actually written into byteData.
Try this instead:
public void SendMessage(Activity activityCode, String inputedString)
{
byte[] data = readMessage.WriteData(activityCode, inputedString);
if (data != null)
{
Debug.Log($"sending {data.Length} bytes");
try
{
clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, serverEndpoint, new AsyncCallback(OnSend), null);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Array.Clear(readMessage.data, 0, readMessage.data.Length);
}
private void OnSend(IAsyncResult ar)
{
try
{
int numBytes = clientSocket.EndSendTo(ar);
Debug.Log($"sent {numBytes} bytes");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void StartReceiveingData()
{
try
{
if (!serverSocket.IsBound)
{
serverSocket.Bind(localServerIPEndPoint);
}
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.BeginReceiveFrom(StaticTest.byteData, 0, StaticTest.byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void OnReceive(IAsyncResult ar)
{
try
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
int numBytes = serverSocket.EndReceiveFrom(ar, ref epSender);
StaticTest.printDData(numBytes);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
StartReceiveingData();
}
static public class StaticTest
{
static public byte[] byteData = new byte[1024];
public static void printDData(int numBytes)
{
Console.WriteLine("Received data: {0}", Encoding.UTF8.GetString(byteData, 0, numBytes));
}
}

How to fix corrupt byte[]-s in win socket

I have two win socket apps, server and client. The server app is at my virtual and client at host machine and the communication is OK. I am sending a ISO file (700MB) through that socket and I came across the error that received bytes are corrupt. When my file come to virtual machine, it has the original size, but the content is not OK. At the client side, I am using this code:
public class ProgramClient
{
public static void StartClient()
{
// Data buffer for incoming data.
byte[] msg;
try
{
IPAddress ipAd = IPAddress.Parse("192.168.137.71");
IPEndPoint remoteEP = new IPEndPoint(ipAd, 1234);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
Console.WriteLine("Client connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Sending file...");
msg = GetBinaryFile(#"C:\TCPIP\test_big.iso");
byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
int msgLength = BitConverter.ToInt32(msgLengthBytes, 0);
Console.WriteLine("int: {0}", msgLength);
Console.WriteLine("msgL size: {0}", msgLengthBytes.Length);
//join arrays, file size info, TCP header
byte[] result = new byte[msgLengthBytes.Length + msgLength];
Buffer.BlockCopy(msgLengthBytes, 0, result, 0, msgLengthBytes.Length);
Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);
//file extension info, TCP Header
byte extension = 2; //file extension code
byte[] newArray = new byte[result.Length + 1];
result.CopyTo(newArray, 1);
newArray[0] = extension;
result = newArray;
int bytesSent = sender.Send(result);
Console.WriteLine("result size: {0}", result.Length);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
private static byte[] GetBinaryFile(string filename)
{
byte[] bytes;
using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
return bytes;
}
public static void Main(String[] args)
{
StartClient();
}
}
At the server side I have the following code:
class ProgramServer
{
public static void Main(String[] args)
{
try
{
StartListening();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
while (true)
{
string outputPath = string.Empty;
outputPath = #"C:\output\output";
Console.WriteLine("Waiting for a connection...");
Socket handler = SocketInstance().Accept();
data = null;
//for the TCP header, get file extension
bytes = new byte[1];
int bytesReceivedExtension = handler.Receive(bytes);
string extension = GetExtension(bytes[0]);
outputPath = outputPath + extension;
//for the TCP header, get file size information
bytes = new byte[4];
int bytesReceived = handler.Receive(bytes);
int Lenght = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("msg length: " + Lenght);
int TotalReceivedBytes = 0;
while (TotalReceivedBytes < Lenght)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
TotalReceivedBytes = TotalReceivedBytes + bytesRec;
AppendAllBytes(outputPath, bytes);
}
Console.WriteLine("Bytes received total: " + TotalReceivedBytes);
Console.WriteLine(File.Exists(outputPath) ? "File received." : "File not received.");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
private static Socket SocketInstance()
{
IPAddress ipAd = IPAddress.Parse("192.168.137.71");
IPEndPoint localEndPoint = new IPEndPoint(ipAd, 1234);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
return listener;
}
public static void AppendAllBytes(string path, byte[] bytes)
{
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write(bytes, 0, bytes.Length);
}
}
public static string GetExtension(byte extOfFile)
{
switch (extOfFile)
{
case 0:
return ".txt";
case 1:
return ".png";
case 2:
return ".iso";
default:
return "";
}
}
}
So, how can I be sure that my byte[] is OK? Because when I open that ISO file at the received side, its content is not OK. IS there some alternative for any type of file to binary conversion?
Thanks.
The framing protocol you made up seems to work like this:
0 1 2 3 4 ... N
[L][L][L][L][D][...][D]
Where L represents an 32-bit integer (in which endianness?) indicating the lenght of the Data.
First, you're sending the wrong file length:
byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
Why do you subtract 3? You shouldn't. This causes the last 3 bytes to be chopped off the file.
Then when filling the message buffer, you start writing at byte 3, or the last byte of L:
Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);
This will cause the reader to interpret an incorrect data length. You should start at byte 4.
Third, when writing the file, you shouldn't append the entire buffer, but only the bytes that Receive() actually wrote in the buffer:
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
TotalReceivedBytes = TotalReceivedBytes + bytesRec;
AppendAllBytes(outputPath, bytes, bytesRec);
Then in that method:
public static void AppendAllBytes(string path, byte[] bytes, int bufferLength)
{
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write(bytes, 0, bufferLength);
}
}
And this is why you shouldn't write your own protocol and socket code if you don't know very well what you're doing. Leverage existing protocols and libraries instead.

Asynchronous sockets in ring transfer

I trying to write program, that combines several machines in ring. And after that I send token around this ring. I have a problem: when marker has passed around the ring once and I want to send it second time, machine doesn't want to accept it marker. Sometimes VS rises exception, sort of "... host forcibly closed the connection". Before this problem did not arise at work with asynchronous sockets...
I guess, that problem in listening socket, that work out 1 time and closed. But how can I fix it?
Thanks in advance for your help.
Function, that initializes machines:
private void connectButton_Click(object sender, EventArgs e)
{
if (!connected)
{
//some operation
}
else
{
//some operation
}
try
{
sendS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
recieveS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
portFrom = int.Parse(port1TextBox.Text);
portTo = int.Parse(port2TextBox.Text);
}
catch (Exception)
{
port1TextBox.Text = "Incorrect!";
}
IPAddress ipAddressFrom = IPAddress.Parse("192.168.1.122");
IPEndPoint ipEnd = new IPEndPoint(ipAddressFrom, portFrom); //IPAddress.Any
sendS.Bind(ipEnd);
sendS.Listen(1);
sendS.BeginAccept(new AsyncCallback(accept), null);
}
public void accept(IAsyncResult asyn)
{
Socket sock = sendS.EndAccept(asyn);
// Let the worker Socket do the further processing for the just connected client
begin(sock);
// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
sendS.BeginAccept(new AsyncCallback(accept), null);
}
public class SocketPacket
{
public Socket m_currentSocket;
public byte[] dataBuffer;
// Constructor that takes one argument.
public SocketPacket(int size)
{
dataBuffer = new byte[size];
}
}
public void begin(Socket s)
{
AsyncCallback pfnWorkerCallBack = new AsyncCallback(serialPort1_DataReceived);
SocketPacket theSocPkt = new SocketPacket(15);
theSocPkt.m_currentSocket = s;
s.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
private void serialPort1_DataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = socketData.m_currentSocket.EndReceive(asyn);
byte[] dataBytes = socketData.dataBuffer.ToArray();
for (int i = dataBytes.Length - 1; i > 0; i--)
{
if (dataBytes[i] != 0)
{
Array.Resize(ref dataBytes, i+1);
break;
}
}
Encoding enc = Encoding.GetEncoding(1251);
String text = enc.GetString(dataBytes);
analyze(text);
}
Function, that connects 2 machines:
private void button1_Click(object sender, EventArgs e)
{
if (connected)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipTo.Text), System.Convert.ToInt32(portTo));
recieveS.Connect(ip);
}
}
Ok. Solved. I forgot about string
begin(socketData.m_currentSocket);
at the end serialPort1_DataReceived function...

if condition in asynchronous socket programming

How can I use if condition in asynchronous socket programming.
For example if client sends "hello" then server response is "hi" and if client send "how r u" then server send "i am fine".
I have this code and I am trying to do that, but it does not work.
Please tell where i need to change my code.
Thanks in Advance
Here is server code
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8888);
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
if (content == "hello")
{
Console.WriteLine(content);
Send(handler, content);
}
else if (content == "How r u")
{
Console.WriteLine(content);
Send2(handler, content);
}
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
data = "Hi";
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}
private static void Send2(Socket handler, String data)
{
data = "fine";
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
content == "How r u" and content == "hello" check the object equality by comparing there references. content and your const strings are not in the same memory (not the same objects).
To compare there content call content.compareTo("How r u")==0.
I solved it. I just have to put < eof > at the end of 'hello' like "hello< eof >" and same to how r u. Its work now.