sockets seems to not work on two computers - sockets

i've faceing a weird problem i wrote a c# simple chat app and it works perfect when i launch the 2 clients on 1 machine but when i try one on my laptop(other computer but same ip) or send it to my friend it's just not working... we both turned off the firewall
thats the server code(part of it which i think can be the problem)
private void StartListening()
{
listener = new TcpListener(IPAddress.Any, listenport);
listener.Start();
while (true) {
try
{
Socket s = listener.AcceptSocket();
clientsocket = s;
clientservice = new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString() );
}
}
//listener.Stop();
}
and that's the client code
private void EstablishConnection()
{
statusBar1.Text = "Connecting to Server";
try
{
clientsocket = new TcpClient("10.0.0.3",serverport);
ns = clientsocket.GetStream();
sr = new StreamReader(ns);
connected = true;
}
catch (Exception e)
{
MessageBox.Show("Could not connect to Server","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
statusBar1.Text = "Disconnected";
}
}
private void RegisterWithServer()
{
try
{
string command = "CONN|" + ChatOut.Text;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
string serverresponse = sr.ReadLine();
serverresponse.Trim();
string[] tokens = serverresponse.Split(new Char[]{'|'});
if(tokens[0] == "LIST")
{
statusBar1.Text = "Connected";
btnDisconnect.Enabled = true;
}
for(int n=1; n<tokens.Length-1; n++)
lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'}));
this.Text = clientname + ": Connected to Chat Server";
}
catch (Exception e)
{
MessageBox.Show("Error Registering","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ReceiveChat()
{
bool keepalive = true;
while (keepalive)
{
try
{
Byte[] buffer = new Byte[2048];
ns.Read(buffer,0,buffer.Length);
string chatter = System.Text.Encoding.ASCII.GetString(buffer);
string[] tokens = chatter.Split(new Char[]{'|'});
if (tokens[0] == "CHAT")
{
rtbChatIn.AppendText(tokens[1]);
if(logging)
logwriter.WriteLine(tokens[1]);
}
if (tokens[0] == "PRIV") {
rtbChatIn.AppendText("Private from ");
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(tokens[2] + "\r\n");
if(logging){
logwriter.Write("Private from ");
logwriter.Write(tokens[1].Trim() );
logwriter.WriteLine(tokens[2] + "\r\n");
}
}
if (tokens[0] == "JOIN")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has joined the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has joined the Chat");
}
string newguy = tokens[1].Trim(new char[]{'\r','\n'});
lbChatters.Items.Add(newguy);
}
if (tokens[0] == "GONE")
{
rtbChatIn.AppendText(tokens[1].Trim() );
rtbChatIn.AppendText(" has left the Chat\r\n");
if(logging){
logwriter.WriteLine(tokens[1]+" has left the Chat");
}
lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'}));
}
if (tokens[0] == "QUIT")
{
ns.Close();
clientsocket.Close();
keepalive = false;
statusBar1.Text = "Server has stopped";
connected= false;
btnSend.Enabled = false;
btnDisconnect.Enabled = false;
}
}
catch(Exception e){}
}
}
private void QuitChat()
{
if(connected) {
try{
string command = "GONE|" + clientname;
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
clientsocket.Close();
}
catch(Exception ex){
}
}
if(logging)
logwriter.Close();
if(receive != null && receive.IsAlive)
receive.Abort();
this.Text = "ChatClient";
}
private void StartStopLogging()
{
if(!logging){
if(!Directory.Exists("logs"))
Directory.CreateDirectory("logs");
string fname = "logs\\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
FileAccess.Write));
logging = true;
btnLog.Text = "Stop Logging";
statusBar1.Text = "Connected - Log on";
}
else{
logwriter.Close();
logging = false;
btnLog.Text = "Start Logging";
statusBar1.Text = "Connected - Log off";
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(String[] args)
{
ChatClientForm cf = new ChatClientForm();
if(args.Length == 0)
cf.serveraddress = "localhost";
else
cf.serveraddress = args[0];
Application.Run(cf);
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
if(ChatOut.Text == ""){
MessageBox.Show("Enter a name in the box before connecting","Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else
clientname = ChatOut.Text;
EstablishConnection();
if(connected)
{
RegisterWithServer();
receive = new Thread(new ThreadStart(ReceiveChat));
receive.Start();
btnSend.Enabled = true;
btnConnect.Enabled = false;
ChatOut.Text = "";
}
im breaking my head over 2 weeks with that... please someone help... :(

basically you have a device on your network (It is probably 10.0.01 or 10.0.0.254, but it could be something else). This is probably either your router / cablemodem / dsl modem. This allows you to do Network Address Translation / Port Address Translation (NAT/PAT). Which allows you to share 1 Public /WAN IP address (79.181.175.247) with all of the computers on your LAN (10.0.0.*). It does this by remapping all of your connections outbound to share the one address, and it keeps track of all of these connections. So when your computer goes out to connect to the internet (say browse a website). It connects from from 10.0.0.3 port 45356 to say google.com port 80. The firewall then maps the request to come from 79.181.175.247 port 5634 and sends the packet to google, and keeps track that return traffic to port 5634 maps to 10.0.0.3 port 45356, so it sends it back to the requesting host.
A side effect is that inbound connections don't know where to go. So for example if your serverport is 1234 on your chat program,and it is listening on 0.0.0.0 of your laptop (10.0.0.3). Your Firewall/Router (10.0.0.1?) doesn't know about this port (there are mechanisms, such as UPNP to communicate this up to compatible routers, but that is outside the scope of this). So you need to manually tell your router/firewall that any connections on the public IP address on port 1234 should be forwarded to port 1234 on your laptop. Depending upon the firewall/router this can have different names. Could be Port Forward, or could be called a mapping, etc... This is required so that the inbound traffic makes it directly to your program.
If you where to try this on your local lan (With firewalls disabled on your computer), you would need to use your internal IP addresses (10.0.0.x) to connect between laptop and other computer (you said same IP, but internally they need to have different addresses, or else they won't work).

Related

Xamarin Forms Artnet and UDP transmission

I'm creating a cross platform application that uses Artnet and UDP protocol to communicate with a device on the network. I know Artnet is also UDP.
Where it works:
Windows OS:
Ethernet. Direct Link and Router controlled.
Wifi. Direct Link and Router Controlled.
Android OS:
Ethernet. N/A
Wifi. Direct Link only.
iOS:
Ethernet. N/A
Wifi. Direct Link only.
Don't understand why there's 0 communication when there's a router involved on Android and iOS. I tried all the suggested codes I could find online and ticked all the capabilities that I could find for Android and iOS.
Wireshark shows there is transmission going on, but my App doesn't capture the packets.
Snipets:
var artnet = new ArtNetSocket(); // using System.Net.Sockets;
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
artnet.Bind(new IPEndPoint(LocalIP, 6454));
artnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
EndPoint localPort = new IPEndPoint(IPAddress.Any, Port);
ArtNetData data= new ArtNetData();
artnet.BeginReceiveFrom(recieveState.buffer, 0, recieveState.bufferSize, SocketFlags.None, ref localPort, new AsyncCallback(WhenRecieved), data);
private void WhenRecieved(IAsyncResult state)
{
//1.Do something when received
//2.Begin receive again
}
How I look for IPs:
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
if (Interface.NetworkInterfaceType != NetworkInterfaceType.Loopback )
{
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (var info in UnicastIPInfoCol)
{
if (info.Address.AddressFamily == AddressFamily.InterNetwork)
{
IPsets.Add(new IPCouples(info.Address, info.IPv4Mask));
}
}
}
}
It's so weird it's probably something simple...
Ok, because I was creating sockets for each IP group, packets weren't captured on public networks, unless the APP was on a Microsoft OS device. If I create a UDPClient and bind it to a port, instead of the localIP address, it will capture everything coming on that port, regardless of the sender's IP Address. If you check the IP address of the socket, it will be 0.0.0.0:PortNumber.
public class Something: UdpClient
{
public int LocalPort;
public Something(int LocalPort) : base(LocalPort)
{
EnableBroadcast = true;
this.LocalPort = LocalPort;
StartListening();
}
private void StartListening()
{
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
StateObject state = new StateObject();
state.workSocket = Client;
BeginReceive(received, state);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
private void received(IAsyncResult ar)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
StateObject state = (StateObject)ar.AsyncState;
var message = EndReceive(ar, ref remoteEndPoint);
if (message.Length > 0)
{
var messageString = (Encoding.UTF8.GetString(message));
//Do Something
}
StartListening();
}
public SendToAll(string message)
{
var callMessage = Encoding.ASCII.GetBytes(message);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
EnableBroadcast = true;
Send(callMessage, callMessage.Length, new IPEndPoint(GetBroadcast(UnicatIPInfo.Address,UnicatIPInfo.IPv4Mask) , LocalPort));
}
}
}
private IPAddress GetBroadcast(IPAddress someAddress, IPAddress someMask)
{
//Do something to get broadscat
return Broadcast;
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
It works on all platform. Carefull which port you use.

Xamarin Forms Socket connection using IPV6 address

I have a sample Socket application that communicates between two devices using and IP address and port. The IPV4 IP-addresses work fine in the application but I cannot seem to get the correct information for the IPV6 IP-addresses.
I believe I understand what is being talked about in this article with regarding to the Zone ID for an IPV6 address
https://howdoesinternetwork.com/2013/ipv6-zone-id
and I also believe I understand what is being said here within that document:
If you want to ping a neighbor computer, you will need to specify the neighbor’s IPv6 Link-Local address plus the Zone ID of your computer’s network adapter that is going towards that computer.
i.e. I need to use the remote IPV6 address with the local device's Zone ID.
My problem is I cannot seem to figure out what the local device's (ios, android) Zone ID is for IPV6 addresses. I have uploaded my sample Xamarin Forms socket server and client code to GitHub and it can be accessed here.
Server Code: https://github.com/gceaser/AsyncSocket
Client Code: https://github.com/gceaser/AsyncSocketClient
I have the IP Addresses and ports defined in the App.xaml.cs for each project and a switch in each project to go back and forth between an IP V4 and V6 connection. (You should update the IP Addresses for your environment if you are trying to test this.) The V4 connection works but I cannot get the V6 connection to work. Any help would be greatly appreciated.
NOTE: To the best of my knowledge you cannot run the client and server on the same windows machine. Something weird about sockets not being able to communicate that way as I have document in one of my other StackOverflow post. Thus to test please run the server on a Windows box and the Client within iOS.
UPDATE:
Here is the code for the Server Socket connection:
using System;
using
System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Collections.Generic;
namespace AsyncSocketServer
{
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public delegate void onMessageReceivedComplete(object sender, string message);
public delegate void onResponseMessageSent(object sender, string message);
public static event onMessageReceivedComplete MessageReceivedComplete;
public static event onResponseMessageSent ResponseMessageSent;
public AsynchronousSocketListener()
{
}
public async static Task StartListening(IPAddress pobj_IPAddress, int pi_Port)
{
try
{
//IPAddress ipAddress = IPAddress.Parse(pobj_IPAddress);
IPEndPoint localEndPoint = new IPEndPoint(pobj_IPAddress, pi_Port);
Socket listener = new Socket(pobj_IPAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
//ViewModelObjects.AppSettings.SocketStatus = ge_SocketStatus.e_Listening;
await Task.Delay(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Debug.WriteLine("Waiting for a connection on " + pobj_IPAddress + " at port " + pi_Port.ToString() + "...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Debug.WriteLine("StartListening Error" + e.ToString());
}
Debug.WriteLine("Read To end class");
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//If we have shut down the socket dont do this.
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
Debug.WriteLine("AcceptCallback Error" + e.ToString());
}
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
string ls_ReceivedCommunicationContent = string.Empty;
string ls_ReturnCommunicationContent = string.Empty;
//string content = string.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
ls_ReceivedCommunicationContent = state.sb.ToString();
if (ls_ReceivedCommunicationContent.IndexOf("<EOF>") > -1)
{
//We need to take off the end of file marker
string ls_WorkContent = ls_ReceivedCommunicationContent.Replace("<EOF>", "");
ls_ReturnCommunicationContent = ls_WorkContent;
//Different than app
Device.BeginInvokeOnMainThread(() => {
MessageReceivedComplete(null, ls_WorkContent);
});
Send(handler, ls_ReturnCommunicationContent);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
catch (Exception e)
{
Debug.WriteLine("ReadCallback Error" + e.ToString());
}
}
private static void Send(Socket handler, String data)
{
try
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
Device.BeginInvokeOnMainThread(() => {
ResponseMessageSent(null, data);
});
}
catch (Exception e)
{
Debug.WriteLine("Send Error" + e.ToString());
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Debug.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Debug.WriteLine("SendCallback Error" + e.ToString());
}
}
}
}
Here is the client Code:
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace AsyncSocketClient
{
// This template use base socket syntax to change Pattern. (like Send, Receive, and so on)
// Convert to Task-based Asynchronous Pattern. (TAP)
public static class AsynchronousClientSocket
{
public static async Task<string> SendMessage(string ps_IPAddress, int pi_Port, string ps_Message)
{
string ls_response = "";
try
{
string ls_ReturnMessage = "";
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
var client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
var isConnect = await client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
if (!isConnect)
{
Console.WriteLine("Can not connect.");
return ls_ReturnMessage;
}
// Send test data to the remote device.
var bytesSent = await client.SendAsync(ps_Message + "<EOF>").ConfigureAwait(false);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Receive the response from the remote device.
ls_response = await client.ReceiveAsync().ConfigureAwait(false);
// Write the response to the console.
Console.WriteLine("Response received : {0}", ls_response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return ls_response;
}
private static Task<bool> ConnectAsync(this Socket client, IPEndPoint remoteEndPoint)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint));
return Task.Run(() => Connect(client, remoteEndPoint));
}
private static bool Connect(this Socket client, EndPoint remoteEndPoint)
{
if (client == null || remoteEndPoint == null)
return false;
try
{
client.Connect(remoteEndPoint);
return true;
}
catch (Exception)
{
return false;
}
}
private static async Task<string> ReceiveAsync(this Socket client, int waitForFirstDelaySeconds = 3)
{
if (client == null) throw new ArgumentNullException(nameof(client));
// Timeout for wait to receive and prepare data.
for (var i = 0; i < waitForFirstDelaySeconds; i++)
{
if (client.Available > 0)
break;
await Task.Delay(1000).ConfigureAwait(false);
}
// return null If data is not available.
if (client.Available < 1)
return null;
// Size of receive buffer.
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
// Get data
var response = new StringBuilder(bufferSize);
do
{
var size = Math.Min(bufferSize, client.Available);
await Task.Run(() => client.Receive(buffer)).ConfigureAwait(false);
response.Append(Encoding.ASCII.GetString(buffer, 0, size));
} while (client.Available > 0);
// Return result.
return response.ToString();
}
private static async Task<int> SendAsync(this Socket client, string data)
{
var byteData = Encoding.ASCII.GetBytes(data);
return await SendAsync(client, byteData, 0, byteData.Length, 0).ConfigureAwait(false);
}
private static Task<int> SendAsync(this Socket client, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (client == null) throw new ArgumentNullException(nameof(client));
return Task.Run(() => client.Send(buffer, offset, size, socketFlags));
}
}
}
When I start the serer, switch it to IPV6 and start it, I get the message that it is waiting for a connection as follows:
Waiting for a connection on fe80::cda4:ea52:29f5:2c7c at port 8080...
When I start the Client, switch it to IPV6 and attempt to send a message, I get the error:
2020-06-19 09:32:51.029902-0400 AsyncSocketClient.iOS[33593:9360848] Can not connect.

simcard message trans/receiver simulator

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?

Raspberry pi 2 server does not respond

I have started a client server project with my raspberry pi 2 running windows 10 IoT which is very nice because you can run the same application on both the PC and the RPI2. With that in mind I only created one application that could act as both client and server which I then deploy on both devices and use one of them as server and the other as Client. The only problem is that server side never answers the clients connect call.
My code is as follows:
Server:
///servername is the port that I use
///hostadapter is an adapter helper obj that has a HostName property set to my Ip address.
public async void Start(string serverName, HostName hostAdapter)
{
//create the "server" object
serverListener = new StreamSocketListener();
serverListener.ConnectionReceived += ServerListener_ConnectionReceived;
try
{
await serverListener.BindEndpointAsync(hostAdapter, serverName);
Started = true;
}
catch (Exception ee)
{
Started = false;
myConsole.Print("error while starting server: " + ee.Message);
}
}
private async void ServerListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
myConsole.Print("connection recieved callback called");
DataReader reader = new DataReader(args.Socket.InputStream);
DataWriter ServerWriter = new DataWriter(args.Socket.OutputStream);
string ServerAnswer = "message recieved by server";
try
{
while (true)
{
// Read first 4 bytes (length of the subsequent string).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the string.
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringLength);
if (stringLength != actualStringLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
ServerWriter.WriteUInt32(ServerWriter.MeasureString(ServerAnswer));
ServerWriter.WriteString(ServerAnswer);
await ServerWriter.StoreAsync();
}
}
catch (Exception exception)
{
myConsole.Print(exception.Message);
}
}
Client:
public async void Connect(string serverIP, string serverPort)
{
try
{
ServerHost = new HostName(serverIP);
}
catch (Exception ee)
{
return;
}
try
{
//open socket
ClientSocket = new StreamSocket();
await ClientSocket.ConnectAsync(ServerHost, serverPort);
Connected = true;
}
catch (Exception ex)
{
ClientSocket.Dispose();
ClientSocket = null;
myConsole.Print(ex.Message);
Connected = false;
}
}
Any help is much appreciated. I have downlaoded wireshark to be able to monitor the networkdata and I have located the tcp [syn] package that the client sends, but I can´t see any tcp [syn ack] packages.
It turned out that I was missing one capability. The capabilities that you need to communicate over ethernet are
<Capabilities>
<Capability Name="internetClient" />
<Capability Name="privateNetworkClientServer" />
<Capability Name="internetClientServer" />
</Capabilities>
I hade only added privateNetworkClientServer and internetClient..

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...