A request to send or receive data was disallowed because the socket is not connected - wcf

I am trying to connect to a remote external server using TCP sockets in WCF code
My WCF service is the client which has code using sockets to connect to an external server.
This code sends a request to an external server and receives the server response
int byteCount = 0;
Socket m_socClient;
try
{
string query = "My Request String";
m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse("127:0:0:0");
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, 1234);
EVCommon.Log("COnnecting to" + IPSelected + Port);
m_socClient.Connect(remoteEndPoint);
try
{
if (m_socClient.Connected)
{
EVCommon.Log("Connected to" + IPSelected + Port);
var reQuestToSend = string.Format("POST /ZZZZZ HTTP/1.1\r\nContent-Length:{0}\r\n\r\n{1}", query.Length, query);
byte[] bytesToSend = Encoding.ASCII.GetBytes(reQuestToSend);
byteCount = m_socClient.Send(bytesToSend, SocketFlags.None);
byte[] bytesReceived = new byte[1024];
byteCount = m_socClient.Receive(bytesReceived, SocketFlags.None);
Response271 = Encoding.ASCII.GetString(bytesReceived);
m_socClient.Disconnect(false);
m_socClient.Close(5000);
}
}
catch(Exception ex)
{
EVCommon.Log(ex.Message);
}
}
If I make a windows application with the same client code to connect to the remote server, it is successful. I am able to connect, send and receive
This error occurs only when I bring WCF into the picture. The code fails at if(m_socket.Connected). So it is not able to connect successfully.
A request to send or receive data was disallowed because the socket
is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
Thank you

The difference is that the windows applications runs in the identity of the logged in user and the WCF service runs in the identity of the application pool.
What is probably happening is that the application pool is running as NETWORK SERVICE which does not have the right to open a port.
Try changing the identity of the app pool to your user to check if this is the problem.

Related

Why is the Ignite port listening not authenticated?

org.apache.ignite.internal.util.nio.GridNioServer#createSelector
// Create a new selector
selector = SelectorProvider.provider().openSelector();
if (addr != null) {
// Create a new non-blocking server socket channel
srvrCh = ServerSocketChannel.open();
srvrCh.configureBlocking(false);
if (sockRcvBuf > 0)
srvrCh.socket().setReceiveBufferSize(sockRcvBuf);
// Bind the server socket to the specified address and port
srvrCh.socket().bind(addr);
// Register the server socket channel, indicating an interest in
// accepting new connections
srvrCh.register(selector, SelectionKey.OP_ACCEPT);
}
return selector;
Why is the Ignite port listening not authenticated?
How can I set authentication?
Two parts:
It has to open the connection so that it can be told what the credentials are. If they're not valid, Ignite will disconnect
Ignite can only authenticate thin-clients out-of-the-box. I have not checked the code, but this could be a server or thick-client code path

Connecting to Amazon ActiveMQ with username & password

I'm trying to connect to ActiveMQ Amazon broker via SSL. My application is written in C#.
Previously, I connected via TCP to localhost ActiveMQ broker, which worked:
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;
void Connect()
{
String brokerUri = "activemq:tcp://" + host + ":" + port + "? transport.useLogging=true&wireFormat.maxInactivityDuration=0&userName=myUsername&password=myPassword";
NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);
IConnection connection = factory.CreateConnection();
connection.Start();
}
To connect to ActiveMQ Amazon broker via SSL, I have modified the code in the following way:
void Connect()
{
String brokerUri = "ssl://" + host + ":" + port + "? transport.useLogging=true&wireFormat.maxInactivityDuration=0&userName=myUsername&password=myPassword";
SslTransportFactory transportFactory = new SslTransportFactory();
Uri uri = new Uri(brokerUri);
ITransport transport = transportFactory.CreateTransport(uri);
transport.Command = Command;
transport.Exception = Exception;
transport.Start();
ConnectionFactory factory = new ConnectionFactory(brokerUri);
IConnection connection = factory.CreateConnection();
Connection con = (Connection)connection;
con.ITransport = transport;
con.Start(); => Here the exception is thrown: User name [null] or password is invalid.
}
private void Exception(ITransport sender, Exception command)
{
}
private void Command(ITransport sender, Command command)
{
}
However, upon starting the connection, User name [null] or password is invalid. Exception is thrown.
Please advise.
You're currently passing user credentials via the URI. However, I don't see any reference to username or password in the URI reference documentation. Also, the fact that the exception indicates the user name is null indicates the user credentials in your URI are simply being ignored.
Instead you should pass the user credentials in the CreateConnection method as documented here, e.g.:
IConnection connection = factory.CreateConnection("myUsername", "myPassword");

reply does not work in nservicebus

guys
I'm trying to send message to server and get response on client side, also I'm trying to publish another message on server using the same endpoint.
I don't get response on client side, but subscribers get published messages with success
Server side code:
if (!someCondition)
{
_bus.Reply(new BookingStatus(message, Status.Occupied));
}
else
{
_bus.Reply(new BookingStatus(message, Status.Ok));
_bus.Publish(new RoomBooked(message, Guid.NewGuid()));
//some logic
}
Code for config bus:
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("NServiceBusDemo");
busConfiguration.UseTransport<MsmqTransport>();
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.EnableInstallers();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.AutoSubscribe();
DefaultFactory defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Directory(#"..\..\..\logs");
defaultFactory.Level(LogLevel.Warn);
var bus = Bus.Create(busConfiguration);
return bus;

Aut discovering of ip address

I have a server and a client that communicate with each other over an UDP socket. The server are opening port 10002 and are listening for incoming datagrams.
For the client to get the server ip it sends one broadcast datagram which the server responds to. The client code responsible for finding the ip address of the server looks like this:
private IPEndPoint GetServerEP(TimeSpan timeout, UdpClient udpclient)
{
IPEndpoint server = new IPEndPoint(IPAddress.Broadcast, 10002);
byte[] data = GetDiscoverDatagram();
_udpclient.EnableBroadcast = true;
udpclient.Send(data, data.Length, server);
try
{
udpclient.Client.ReceiveTimeout = (int)timeout.TotalMilliseconds;
udpclient.Receive(ref server);
}
catch (SocketException e)
{
string msg = string.Format("Server did not respond within {0} ms", timeout.TotalMilliseconds);
throw new TimeoutException(msg, e);
}
return server;
}
Upon running this, I can see that the server actually receives the broadcast datagram and responds with a packet bound for the same port as the client sends from. However, the client does not receive anything and timeouts.
What am I missing?
Stupid me (or; stupid firewall). The code worked, but the firewall blocked the response packet from the server. After disabling everything works like a charm.

Cross domain policy file over net.tcp for WCF servicehost and Silverlight 5

I have a locally hosted WCF service and a silverlight 5 app that communicates with it. By default silverlight tries to obtain the cross domain policy file over HTTP when making calls to the WCF service. I need to change this so that the policy file is served over net.tcp port 943 instead.
I have setup a local tcp listener that serves up the policy file over port 943 and i have followed this technique whereby i make a dummy socket connection in order to obtain the policy file over tcp as it is only retrieved once per application lifetime. The tcp server is being hit as expected and i am getting SocketError property value as Success (though i must note, the first time i hit the tcp server after starting the listener, the result is always access denied).
From what i can tell, the policy file is either invalid as the silverlight application as still unable to connect or the above mentioned technique does not work with silverlight 5.
What i would like to know is if what i am doing is possible & im doing it correctly, otherwise if there is an alternative means to have the policy file successfully downloaded over tcp and removing the need for retrieving it over HTTP.
Thanks
I wrote a long post about hosting silverlight in WPF - and using WCF with a http listener here:
How can I host a Silverlight 4 application in a WPF 4 application?
Now while not directly answering your question, it does show how to create a http version of the policy file.
I have also written something that serves up a policy listener over port 943, but I can't find where I posted the source - so I'll keep digging. As far as I remember though, silverlight does a cascade find of the policy file, if it doesn't get a connection on port 80, it'll then look on port 943.
I hope this is of some help somewhere.
Ok, here is the policy listener I had for net.TCP transport i.e. not HTTP based. I presume you have sorted this by now, sorry for the delay. It may well be of use to someone else now.
I was looking for the MS thing that said they cascade from HTTP to TCP, however, I can't, and therefore have to assume it was bunk and then changed.
Either way, if you call using a net.TCP service, and want a listener for it, this code should help:
#region "Policy Listener"
// This is a simple policy listener
// that provides the cross domain policy file for silverlight applications
// this provides them with a network access policy
public class SocketPolicyListener
{
private TcpListener listener = null;
private TcpClient Client = null;
byte[] Data;
private NetworkStream netStream = null;
private string listenaddress = "";
// This could be read from a file on the disk, but for now, this gives the silverlight application
// the ability to access any domain, and all the silverlight ports 4502-4534
string policyfile = "<?xml version='1.0' encoding='utf-8'?><access-policy><cross-domain-access><policy><allow-from><domain uri='*' /></allow-from><grant-to><socket-resource port='4502-4534' protocol='tcp' /></grant-to></policy></cross-domain-access></access-policy>";
// the request that we're expecting from the client
private string _policyRequestString = "<policy-file-request/>";
// Listen for our clients to connect
public void Listen(string ListenIPAddress)
{
listenaddress = ListenIPAddress;
if (listener == null)
{
listener = new TcpListener(IPAddress.Parse(ListenIPAddress), 943);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,lo);
}
listener.Start();
WaitForClientConnect();
}
private void WaitForClientConnect()
{
listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), listener);
}
public void StopPolicyListener()
{
if (Client.Connected)
{
// Should never reach this point, as clients
// are closed if they request the policy
// only clients that open the connection and
// do not submit a policy request will remain unclosed
Client.Close();
}
listener.Stop();
}
public void RestartPolicyListener()
{
listener.Start();
}
// When a client connects:
private void OnClientConnected(IAsyncResult ar)
{
if (ar.IsCompleted)
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
// End the operation and display the received data on
// the console.
Client = listener.EndAcceptTcpClient(ar);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Set our receive callback
Data = new byte[1024];
netStream = Client.GetStream();
netStream.BeginRead(Data, 0, 1024, ReceiveMessage, null);
}
WaitForClientConnect();
}
// Read from clients.
public void ReceiveMessage(IAsyncResult ar)
{
int bufferLength;
try
{
bufferLength = Client.GetStream().EndRead(ar);
// Receive the message from client side.
string messageReceived = Encoding.ASCII.GetString(Data, 0, bufferLength);
if (messageReceived == _policyRequestString)
{
// Send our policy file, as it's been requested
SendMessage(policyfile);
// Have to close the connection or the
// silverlight client will wait around.
Client.Close();
}
else
{
// Continue reading from client.
Client.GetStream().BeginRead(Data, 0, Data.Length, ReceiveMessage, null);
}
}
catch (Exception ex)
{
throw new Exception(Client.Client.RemoteEndPoint.ToString() + " is disconnected.");
}
}
// Send the message.
public void SendMessage(string message)
{
try
{
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
//Client.Client.Send(bytesToSend,SocketFlags.None);
Client.GetStream().Write(bytesToSend,0, bytesToSend.Length);
Client.GetStream().Flush();
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion