I'm using the WCF4.0 template -REST. I'm trying to make a method that uploads a file using a stream.
The problem always occur at
Stream serverStream = request.GetRequestStream();
Class for streaming:
namespace LogicClass
{
public class StreamClass : IStreamClass
{
public bool UploadFile(string filename, Stream fileStream)
{
try
{
FileStream fileToupload = new FileStream(filename, FileMode.Create);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
}
catch (Exception ex) { throw new Exception(ex.Message); }
return true;
}
}
}
REST project:
[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
LogicClass.FileComponent rest = new LogicClass.FileComponent();
return rest.AddStream(filename, fileStream);
}
Windows Form project: for testing
private void button24_Click(object sender, EventArgs e)
{
byte[] fileStream;
using (FileStream fs = new FileStream("E:\\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
fileStream = new byte[fs.Length];
fs.Read(fileStream, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
}
string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
request.Method = "POST";
request.ContentType = "text/plain";
Stream serverStream = request.GetRequestStream();
serverStream.Write(fileStream, 0, fileStream.Length);
serverStream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
}
}
I've turned off the firewall and my Internet connection, but the error still exists. Is there a better way of testing the uploading method?
Stack trace:
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
"Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. It is therefore not a problem in your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port. This may be because it is not running at all or because it is listening on a different port.
Once you start the process hosting your service, try netstat -anb (requires admin privileges) to verify that it is running and listening on the expected port.
update: On Linux you may need to do netstat -anp instead.
You don't have to restart the PC. Restart IIS instead.
Run -> 'cmd'(as admin) and type "iisreset"
You must set up your system proxy
You have to go through this path
controlpanel>>internet option>>connnection>>LAN settings>>
proxy
no tik:use proxy server
I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.
You can test your code in the below two ways.
Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
Change your server port to another port that is also available in the system. You will find the same error code reported.
Above is my fix. It works on my machine. I hope it helps!
Check if any other program is using that port.
If an instance of the same program is still active, kill that process.
I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:
HTTP could not register URL http://+:12345/Foo.svc/]. Your process does
not have access rights to this namespace (see
http://go.microsoft.com/fwlink/?LinkId=70353 for details).
Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258
If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.
I use this tool to do this; it automates all those cumbersome steps.
Check whether the port number in file Web.config of your webpage is the same as the one that is hosted on IIS.
I had the same problem on my web server "No connection could be made because the target machine actively refused it 161.x.x.235:5672". I asked the Admin to open the port 5672 on the web server, then it worked fine.
I had a similar problem
rejecting localhost and 127.0.0.1.
cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5.
after putting in this IP it worked.
This Gives correct IP:
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());
I also faced problem in .Net Remoting Service in C#.
I got it solved in 3 steps:
Change Port of Protocol in all the files whereever it is being used.
Run your Host Server Program and make it active.
Now run your client program.
I could not restart IIexpress. This is the solution that worked for me
Cleaned the build
Rebuild
With this error I was able to trace it, thanks to #Yaur, you need to basically check the service (WCF) if it's running and also check the outbound and inbound TCP properties on your advance firewall settings.
With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.
Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
Resolution: Set the proxy in Web config.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
I had a similar issue. In my case VPN proxy app such as Psiphon ، changed the proxy setup in windows so follow this :
in Windows 10, search change proxy settings and turn of use proxy server in the manual proxy
Make Sure all services used by your application are on, which are using host and port to utilize them . For e.g, as in my case, This error can come, If your application is utilizing a Redis server and it is not being able to connect to it on given port and host, thus producing this error .
For my case, I had an Angular SLA project template with ASP.NET Core.
I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.
The problem, in this case, wasn't connected with the Firewall blocking the connection.
It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.
For more information, check the official Microsoft documentation.
I had similar problem. In launchSettings, my IIS Express was configured on one port, and there was another launch profile that started on another ApplicationUrl with another port.
Starting the web app up with the IIS Express profile led me to have the error.
I am using the Apache ActiveMQ Artemis AMQP message broker. I started getting the "No connection could be made because the target machine actively refused it" exception when trying to send and receive messages with the broker after a reboot. On a computer where the same type of broker still worked, netstat -anb showed that the broker was listening on the expected port 5672. On the computer with the error, the broker was not listening. On the computer with the error, starting the broker resulted in the following warning's appearing in Microsoft Event Viewer's "Windows Logs > System":
The system failed to register host (A or AAAA) resource records for network adapter
with settings:
Adapter Name : {286EE2DA-3D81-41AE-VE5G-5D761FD3925E}
Host Name : mypc
Primary Domain Suffix : myco.com
DNS server list :
55.77.168.1, 74.86.130.1
Sent update to server : 186.952.335.157:45
IP Address(es) :
182.269.1.437
Either the DNS server does not support the DNS dynamic update protocol or the authoritative zone for the specified DNS domain name does not accept dynamic updates.
To register the DNS host (A or AAAA) resource records using the specific DNS domain name and IP addresses for this adapter, contact your DNS server or network systems administrator.
I was able to use the broker without error after I ran the following in a cmd.exe with administrative privileges, rebooted, and waited about fifteen minutes:
ipconfig /flushdns
ipconfig /renew
ipconfig /registerdns
I wrote a php websockets server using the library Ratchet that I call with javascript using the websocket object.
Everything worked perfectly locally but it was impossible to run my project on my Debian server under apache.
To enable websocket connections I read that I have to use mod_proxy_wstunnel module. So I rewrite my apache conf for my subdomain api.domain.com like this:
<VirtualHost *:80>
ServerAdmin admin#admin.admin
DocumentRoot /var/www/api.domain.com
ServerName api.domain.com
# Enable Websocket connections on port 8888
ProxyPass "/wss/homews/" "ws://api.domain.com:8888/"
<Directory /var/www/api.domain.com>
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
Satisfy all
</Directory>
</VirtualHost>
Then I call my php script with this code insight that start Ratchet websocket server:
// ...
// Some code ...
$app = new Ratchet\App('localhost', 8888);
$app->route('/wss/homews/', $myClass, array('*'));
$app->run();
Then when I try to connect to it on the javascript client side with the url ws://api.domain.com:8888/wss/homews/ I always get Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT.
Do you have any ideas how I could debug this type of error ? Are there any logs on apache showing a bad configuration?
Your above configuration has to be changed at least to:
<VirtualHost *:80>
ServerAdmin admin#admin.admin
DocumentRoot /var/www/api.domain.com
ServerName api.domain.com
# Enable Websocket connections on port 8888
ProxyPass "/wss/homews/" "ws://localhost:8888/wss/homews/"
<Directory /var/www/api.domain.com>
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
Satisfy all
</Directory>
</VirtualHost>
And on the javascript client side to the url ws://api.domain.com:80/wss/homews/.
Otherwise probably (or lets say hopefully for a server setup) the target from webserver config api.domain.com:8888 tries to reach upstream the websocket on public IP of the server while websocket is bound to localhost. Eighther it's just not listening there (what is fine as You nromally only want to expose Your webservers ports to the public and not directly Your app ports) or even worse it tries to reach a public NAT IP which involves a trip to a firewall where the port 8888 should be blocked, which may not allow this stuff, can be expensive (eg. AWS EC2) and ist at very least inperformant.
On the other hand You will want to direct the client code to the webserver on port 80 which does the tunnelling to Your websocket app so Your client cannot directly access port 8888 of Your server (it's blocked in the public firewall hopefully - and You are listening on localhost only).
Try with Your original setup and tell how the results changed, maybe there is an additional issue (but You should not get a socket timeout anymore at least and a connection from client to websocket app).
First and foremost, try to simplify things, DO NOT edit or touch any of the configuration files from the server, leave it by default as it is, that will do
I will post all the precautions steps needed in order make the socket up and running, please follow steps one by one, they are as follows:
Check whether your server supports Web Socket on shared hosting, otherwise you may need to go for Dedicated hosting service or Virtual private server(VPS) Eg: AWS, GCP.
If your server supports running a web service scripts like phpwebsocket within a web service, then follow next steps
On the terminal, Update the composer to the latest one, then try to execute $composer require cboden/ratchet
So that the required dependency will load efficiently and do not try to upload any archived dependencies.
In my case, "cboden/ratchet": "^0.4.3" was loaded on localhost, But on production site it was "cboden/ratchet": "^0.4.1"
when compared both from the composer.json file
Try to connect to port 8282, In most cases, the server traffic, both from the inbound & outbound are kept open by default, in case, if the port 8080, could not bind to the TCP
At Last, Try to reboot your cloud hosted server instance and execute the websocket script $php <yourWebSocketScript.php>
I had used mod_proxy_wstunnel to make sure the communications goes encrypted, apart from it,
I was able to up & run the Websocket socketo.me on AWS and our private dedicated server smoothly
Thanks for contacting, I do appreciate your efforts, apart from your concerned comment to reply via johannchopin#protonmaildotcom, this is not my part of the business ethics
Edit
$app = new Ratchet\App('localhost', 8888);
$app->route('/wss/homews/', $myClass, array('*'));
$app->run();
Try changing the manually assigned localhost from your <yourWebSocketScript.php> from the above snippet to
$app = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8282
);
$app->run();
Try binding to the HttpServer, it defaults to localhost or 0.0.0.0 and run (if necessary, eliminate $app->route())
On your code you need to modify
Port Number in yourWebSocketScript.php
Change from localhost to the Server IP or DNS in someChatFilexyz.php
Eg:
let websocket_server = new WebSocket("ws://my.domain.com:8282");
or
let websocket_server = new WebSocket("ws://xxx.xxx.xxx.xxx:8282");
Kill all the previous established socket specific to port 8282 and then run yourWebSocketScript.php
Here is the partial code of someChatFilexyz.php
jQuery(function($){
// Websocket_Controller
var websocket_server = new WebSocket("ws://xxx.xxx.xxx.xxx:8282");
websocket_server.onopen = function(e) {
websocket_server.send(
...
);
};
websocket_server.onerror = function(e) {
// Errorhandling
...
}
websocket_server.onmessage = function(e) {
...
}
}
Setting up the above config, I was able to run on an Amazon Web Service with LAMP stack configured by me and with private dedicated server with ease.
Note: Any minor changes in the code, you need to restart the running websocket script $php <yourWebSocketScript.php> i.e., either by terminating the running process or killing the process specific to port number assigned
I have made a chat with SocketIO who is working well on local, but i'm trying to deploy it on my Apache server.
I'm using Php + NodeJs, not only Node
I had ERR_CONNECTION_REFUSED error but solved it by opening the good port, Listen 8000 in my ports.conf
My server.js look like this
var io = require('socket.io').listen(8000);
// Socket IO usage
My client.js is
var socket = io.connect('http://[MY SERVER IP]:8000');
// Other client code
I use localhost in local but I changed by my server ip.
But I still have this error
XMLHttpRequest cannot load http://[MY_SERVER_IP]:8000/socket.io/?EIO=3&transport=polling&t=1455101301883-60. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'MY DOMAIN' is therefore not allowed access. The response had HTTP status code 404.
I really don't know what to do, this is the first I try to deploy a Nodejs + php app.
I had read some Stackoverflow questions to try to fix it, but i really don't know how...
I don't knwo if this is due to my Apache conf or I must change some NodeJS or SocketIO conf
Thanks for your help.
I found the problem.
Do not open the NodeJS server port on Apache config. It will make some conflicts and will prevent your Node server to work.
Just change the localhost by your server IP and it will work fine.
I currently have two apps at AppFog, they are.
http://sru-forums-prod.aws.af.cm/ and http://sru-home-prod.aws.af.cm/
I have haProxy running locally on my computer, this is my current config file.
global
debug
defaults
mode http
timeout connect 500ms
timeout client 50000ms
timeout server 50000ms
backend legacy
server forums sru-forums-prod.aws.af.cm:80
frontend app *:8232
default_backend legacy
The end-goal is that localhost:8232 forwards traffic to sru-home-prod, while localhost:8232/forums/* forwards traffic to sru-forums-prod. However I cant even get a simple proxy up and running.
When I run HAProxy off this config file I receive AppFog 404 Not Found at localhost:8232.
What am I missing, is this even possible?
EDIT:
New config works but now i have a port 60032 coming back in the response.
global
debug
defaults
mode http
timeout connect 500ms
timeout client 50000ms
timeout server 50000ms
backend legacy
option forwardfor
option httpclose
reqirep ^Host: Host:\ sru-forums-prod.aws.af.cm
server forums sru-forums-prod.aws.af.cm:80
frontend app *:8000
default_backend legacy
The reason you are getting an AppFog 404 Not Found is because applications hosted on AppFog are routed by domain name. In order for AppFog to know what app to serve you, the domain name is required to be in the HTTP request. When you go to localhost:8232/forums/ it sends localhost as the domain name which AppFog does not have as a registered app name.
There is a good way to get around this issue
1) Map your application to a second domain name, for example:
af map <appname> sru-forums-prod-proxy.aws.af.cm
2) Edit your /etc/hosts file and add this line:
127.0.0.1 sru-forums-prod-proxy.aws.af.cm
3) Go to http://sru-forums-prod-proxy.aws.af.cm:8232/forums/ which will map to the local machine but will go through your haproxy successfully ending up with the right host name mapped to your app hosted at AppFog.
Here is a working haproxy.conf file that demonstrates how this has worked for us so far using similar methodologies.
defaults
mode http
timeout connect 500ms
timeout client 50000ms
timeout server 50000ms
backend appfog
option httpchk GET /readme.html HTTP/1.1\r\nHost:\ aroundtheworld.appfog.com
option forwardfor
option httpclose
reqirep ^Host: Host:\ aroundtheworld.appfog.com
server pingdom-aws afpingdom.aws.af.cm:80 check
server pingdom-rs afpingdom-rs.rs.af.cm:80 check
server pingdom-hp afpingdom-hp.hp.af.cm:80 check
server pingdom-eu afpingdom-eu.eu01.aws.af.cm:80 check
server pingdom-ap afpingdom-ap.ap01.aws.af.cm:80 check
frontend app *:8000
default_backend appfog
listen stats 0.0.0.0:8080
mode http
stats enable
stats uri /haproxy