I don't get it, my friend and I are developing an API and our WebSocket services works, but not the mobile side.. I tried with a couple of clients, on the web, our echo messaging and everything works.
The thing is, I mean, the things seem like the socket is mono-directional. I tried the example of https://github.com/rdavisau/sockets-for-pcl#a-tcp-client:
var address = "127.0.0.1";
var port = 11000;
var r = new Random();
var client = new TcpSocketClient();
await client.ConnectAsync(address, port);
// we're connected!
for (int i = 0; i<5; i++)
{
// write to the 'WriteStream' property of the socket client to send data
var nextByte = (byte) r.Next(0,254);
client.WriteStream.WriteByte(nextByte);
await client.WriteStream.FlushAsync();
// wait a little before sending the next bit of data
await Task.Delay(TimeSpan.FromMilliseconds(500));
}
await client.DisconnectAsync();
First, after I get connected with this :
public async void ConnectSocketToAPIAsync()
{
SocketClient = new TcpSocketClient();
await SocketClient.ConnectAsync("my.ws.service", 4242);
ActiveSocketExchange();
}
public async void ActiveSocketExchange()
{
var bytesRead = -1;
var buf = new byte[1];
while (bytesRead != 0)
{
bytesRead = await SocketClient.ReadStream.ReadAsync(buf, 0, 1);
if (bytesRead > 0)
MessagingCenter.Send((App)Current, SOCKET_Message, System.Text.Encoding.UTF8.GetString(buf, 0, bytesRead));
}
}
Everything's fine, my TcpClient is well initialized (even the web-link becomes the http's API addr)
From my page view, when I'm done writing my text, I'm pressing the done button of the keyboard and this code is called:
private void InitSocketPart()
{
MessagingCenter.Subscribe<App, string>((App)Application.Current, App.SOCKET_Message, (sender, text) =>
{
SocketResponseText = text;
});
}
private async void OnTextCompleted(object sender, EventArgs ea)
{
var bytes = Encoding.UTF8.GetBytes(TextToSend);
try {
if (App.SocketClient.WriteStream.CanRead)
Debug.WriteLine("canRead");
if (App.SocketClient.WriteStream.CanWrite)
Debug.WriteLine("canWrite");
App.SocketClient.WriteStream.Write(bytes, 0, TextToSend.Length);
App.SocketClient.WriteStream.Flush();
} catch (Exception e)
{
Debug.WriteLine(e);
}
}
So now CanWrite && CanRead are true, but nothing at all happens, even with the use of Async methods... Why so? I don't get it..
The use of messaging center is just to have only one point of incoming message. I'm using it for other things and it works perfectly :)
Thank for any help..
Related
[Problem]
System.Net.Sockets.Socket's async receiving corrupts the receiving buffer, injecting a random burst of bytes into the middle of the received data.
[Background]
I have a TCP connections server. Clients establish socket connection with the server, and send encrypted packets to server.
Initially, the server operated using threads. Every incoming connection is served by a dedicated thread. All buffers to be sent and received via sockets are allocated on the heap and garbage collected. Everything worked fine.
Then, to improve performance, I did two changes:
Instead of allocating buffers on the heap, I allocated from using ArrayPool.Shared.Rent().
I changed the socket's sending and receiving to async.
I did not change how packets are serialized, deserialized, encrypted and decrypted.
After the change, everything works fine on my development PC. When deployed to production server on AWS, when packets are small (50 bytes or so), everything was fine.
When the packet size is large, 16 KB each, the server will receive a few of such packets fine, then, randomly, one of the received packets will be corrupted, with a burst of a thousand or so unknow bytes injected in the middle of the received data, causing the AES decryption to throw the "invalid padding" exception:
I have no idea where the injected extra bytes come from.
Following are the socket sending and receiving code:
public static Task<int> ReceiveBytesAsync(this Socket socket, SocketAsyncEventArgs args) // , int offset, int count)
{
var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<SocketAsyncEventArgs> handler = null;
handler = (s, e) =>
{
args.Completed -= handler;
if (args.SocketError != SocketError.Success)
tcs.SetException(new InvalidOperationException(args.SocketError.ToString()));
else
tcs.SetResult(args.BytesTransferred);
};
args.Completed += handler;
if (!socket.ReceiveAsync(args))
{
args.Completed -= handler;
if (args.SocketError != SocketError.Success)
tcs.SetException(new InvalidOperationException(args.SocketError.ToString()));
else
tcs.SetResult(args.BytesTransferred);
}
return tcs.Task;
}
private static async Task<bool> ReadBufferFromSocketAsync(Socket socket, SocketAsyncEventArgs socketArgs) // , int offset, int length)
{
for (int bytesRead = 0; bytesRead < socketArgs.Count;)
{
// If bytesRead is 0, SetBuffer would have been called by the caller of this method.
if (bytesRead > 0)
socketArgs.SetBuffer(socketArgs.Offset + bytesRead, socketArgs.Count - bytesRead);
int nRead = await socket.ReceiveBytesAsync(socketArgs);
bytesRead += nRead;
if (nRead == 0)
{
socket.Close();
return false;
}
}
return true;
}
public static Task<int> SendBytesAsync(this Socket socket, SocketAsyncEventArgs args) // , int offset, int count)
{
var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<SocketAsyncEventArgs> handler = null;
handler = (s, e) =>
{
args.Completed -= handler;
if (args.SocketError != SocketError.Success)
tcs.SetException(new InvalidOperationException(args.SocketError.ToString()));
else
tcs.SetResult(args.BytesTransferred);
};
args.Completed += handler;
if (!socket.SendAsync(args)) // means the operation completed synchronously & Completed handler won't fire
{
args.Completed -= handler;
if (args.SocketError != SocketError.Success)
tcs.SetException(new InvalidOperationException(args.SocketError.ToString()));
else
tcs.SetResult(args.BytesTransferred);
}
return tcs.Task;
}
private static async Task<bool> SendBufferToSocketAsync(Socket socket, SocketAsyncEventArgs socketArgs)
{
int retry = 0;
for (int ixWrite = 0; ixWrite < socketArgs.Count;)
{
if (ixWrite > 0)
socketArgs.SetBuffer(socketArgs.Offset + ixWrite, socketArgs.Count - ixWrite);
int nSent = await socket.SendBytesAsync(socketArgs);
ixWrite += nSent;
if (retry >= 10)
{
socket.Close();
return false;
}
if (nSent == 0)
{
retry++;
await Task.Delay(10 * retry);
}
else
retry = 0;
}
return true;
}
Problem disappeared after I changed the ReadBufferFromSocketAsync to the following
private static async Task<bool> ReadBufferFromSocketAsync(Socket socket, byte[] buffer, int offset, int totalToRead)
{
using (SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs())
{
int iAllRead = 0, iOneRead = 0;
socketArgs.SetBuffer(buffer, offset, totalToRead);
while (true)
{
iOneRead = await socket.ReceiveBytesAsync(socketArgs);
if (iOneRead == 0)
{
socket.Close();
return false;
}
iAllRead += iOneRead;
if (iAllRead == totalToRead)
return true;
offset += iOneRead;
socketArgs.SetBuffer(offset, totalToRead - iAllRead);
}
}
}
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.
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?
i made a Async Server Socket Code using C# Socket.
Although i wrote a code, then test to Console Environment,
it was working, but i tested that code at UWP.
but, it was not working. cannot accepts client.
Bind, Listen, Accept there are all no error, but this socket code cannot accepts client!
how can i solve me?? please help me..
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private int m_iPort = 1123;
private int m_iClients = 8;
private int m_iBufferSize = 128;
public bool Open(int IN_iPort, int IN_iClients, int IN_iBufferSize)
{
try
{
m_iPort = IN_iPort;
m_iClients = IN_iClients;
m_iBufferSize = IN_iBufferSize;
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_iPort);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(m_iClients);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
catch (Exception e)
{
return false;
}
m_bIsOpen = true;
return true;
}
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[m_iBufferSize];
args.SetBuffer(szData, 0, m_iBufferSize);
args.UserToken = m_ClientSocket;
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
I have check your code, there seems no issue existing in your code. Please check if you have checked Internet(Clent&Server)option in your project appxmanifest. For more detail you could refer to Sockets official documentation.
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...