Luasocket server and actionscript - actionscript-3

I used an example given on the Luasocket website just to try it out, my goal was to make a flash game that'll communicate with the socket.
I run the server and connected to it using telnet at first and it worked, every message I sent appeared on the console so I took it to the next step and connected to it through AS 3 and it did connect but the server won't receive any message even though I constantly write() to it.
Is there anything I'm missing that won't let an actionscript application communicate with the lua socket server?
Code
-- load namespace
local socket = require("socket")
-- create a TCP socket and bind it to the local host, at any port
local server = assert(socket.bind("*", 0))
-- find out which port the OS chose for us
local ip, port = server:getsockname()
-- print a message informing what's up
print("Please telnet to localhost on port " .. port)
print("After connecting, you have 10s to enter a line to be echoed")
-- loop forever waiting for clients
while 1 do
-- wait for a connection from any client
local client = server:accept()
-- make sure we don't block waiting for this client's line
client:settimeout(10)
-- receive the line
local line, err = client:receive()
-- if there was no error, send it back to the client
if not err then client:send(line .. "\n") end
-- done with client, close the object
client:close()
end
Actionscript:
var sock:Socket = new Socket();
sock.connect("127.0.0.1",3335);
stage.addEventListener(Event.ENTER_FRAME,test);
public function test(e:Event):void{
sock.writeUTF("Hello world");
}

The standard mode of operation of the client:receive() method is "*l", which waits for a new line character in the input stream to return. http://w3.impa.br/~diego/software/luasocket/tcp.html#receive
To correct this, either send "Hello world\n" (assuming it's the correct escape character in actionscript) or use another parameter in receive().

Related

can't connect to MySQL remotely on Windows 10 [duplicate]

Sometimes I get the following error while I was doing HttpWebRequest to a WebService. I copied my code below too.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.
The most probable reason is a Firewall.
This article contains a set of reasons, which may be useful to you.
From the article, possible reasons could be:
FTP server settings
Software/Personal Firewall Settings
Multiple Software/Personal Firewalls
Anti-virus Software
LSP Layer
Router Firmware
Computer Turned Off
Computer Not Plugged In
Fiddler
I had the same. It was because the port-number of the web service was changing unexpectedly.
This problem usually happens when you have more than one copy of the project
My project was calling the Web service with a specific port number which I assigned in the Web.Config file of my main project file. As the port number changed unexpectedly, the browser was unable to find the Web service and throwing that error.
I solved this by following the below steps: (Visual Studio 2010)
Go to Properties of the Web service project --> click on Web tab --> In Servers section --> Check Specific port
and then assign the standard port number by which your main project is calling the web service.
I hope this will solve the problem.
Cheers :)
I think, you need to check your proxy settings in "internet options". If you are using proxy/'hide ip' applications, this problem may be occurs.
I had the same problem. The problem is that I didn't start the selenium server. I have downloaded the selenium server and i started it. After starting the selenium server, issue gone and all worked fine.
Refer this : http://coding-issues.blogspot.in/2012/11/no-connection-could-be-made-because.html
I had the same error with my WCF service using Net TCP binding, but resolved after starting the below services in my case.
Net.Pipe.Listener.Adapter
Net.TCP.Listener.Adapter
Net.Tcp Port Sharing Service
In my case, some domains worked, while some did not. Adding a reference to my organization's proxy Url in my web.config fixed the issue.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy.my-org.com/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
When you call service which has only HTTP (ex: http://example.com) and you call HTTPS (ex: https://example.com), you get exactly this error - "No connection could be made because the target machine actively refused it"
I faced same error because when your Server and Client run on same machine the Client need server local ip address not Public ip address to communicate with server you need Public ip address only in case when Server and Client run on separate machine so use Local ip address in client program to connect with server Local ip address can be found using this method.
public static string Getlocalip()
{
try
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
return localIPs[7].ToString();
}
catch (Exception)
{
return "null";
}
}
I got this error in an application that uses AppFabric. The clue was getting a DataCacheException in the stack trace. To see if this is the issue for you, run the following PowerShell command:
#("AppFabricCachingService","RemoteRegistry") | % { get-service $_ }
If either of these two services are stopped, then you will get this error.
For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)
The process 'MongoDB Service' wasn't running in Services
Start cmd as Administrator and type,
net start MongoDB
Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6" folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6", named my_2014-03-28T15-51-20.ini in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6".
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
For service reference within a solution.
Restart your workstation
Rebuild your solution
Update service reference in WCFclient project
At this point, I received messsage (Windows 7) to allow system access.
Then the service reference was updated properly without errors.
I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx
I implemented this function almost exactly as written, but what happened is I got this error:
2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080
This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!
private Socket ConnectSocket(string server, int port)
{
Socket s = null;
try
{
// Get host related information.
IPAddress[] ips;
ips = Dns.GetHostAddresses(server);
Socket tempSocket = null;
IPEndPoint ipe = null;
ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
s.SendTimeout = Coordinate.HL7SendTimeout;
s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
}
else
{
return null;
}
return s;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
if (g_NoOutputForThreading == false)
rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
return null;
}
}
This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.
One more possibility --
Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.
I've received this error from referencing services located on a WCFHost from my web tier. What worked for me may not apply to everyone, but I'm leaving this answer for those whom it may. The port number for my WCFHost was randomly updated by IIS, I simply had to update the end routes to the svc references in my web config. Problem solved.
In my scenario, I have two applications:
App1
App2
Assumption: App1 should listen to App2's activities on Port 5000
Error: Starting App1 and trying to listen, to a nonexistent ghost town, produces the error
Solution: Start App2 first, then try to listen using App1
Go to your WCF project -
properties ->
->
debuggers
-> unmark the checkbox
Enable Edit and Continue
In my case this was caused by a faulty deployment where a setting in my web.config was not made.
A collegue explained that the IP address in the error message represents the localhost.
When I corrected the web.config I was then using the correct url to make the server calls and it worked.
I thought I would post this in case it might help someone.
Using WampServer 64bit on Windows 7 Home Premium 64bit I encountered this exact problem. After hours and hours of experimentation it became apparent that all that was needed was in my.ini to comment out one line. Then it worked fine.
commented out 1 line
socket=mysql
If you put your old /data/ files in the appropriate location, WampServer will accept all of them except for the /mysql/ folder which it over writes. So then I simply imported a backup of the /mysql/ user data from my prior development environment and ran FLUSH PRIVILEGES in a phpMyAdmin SQL window. Works great. Something must be wrong because things shouldn't be this easy.
I had this issue happening often. I found SQL Server Agent service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:
Run prompt, type services.msc and hit enter
Find the service name - SQL Server Agent(Instance Name)
If SQL Server Agent is not running, double-click the service to open properties window. Then click on Start button. Hope it will help someone.
I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.
It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!
There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.
In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.
I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.
Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.
Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.
Hope it helps.
it might be because of authorisation issues; that was the case for me.
If you have for example: [Authorize("WriteAccess")] or [Authorize("ReadAccess")] at the top of your controller functions, try to comment them out.
I just faced this right now...
Here on my end, I have 2 separated Visual Studio solutions (.sln)... opened each one in their own Visual Studio instance.
Solution 2 calls Solution 1 code. The problem was related to the port assigned to Solution 1. I had to change the port on solution 1 to another one and then Solution 2 started working again. So make sure you check the port assigned to your project.
Normally, connection scripts do not mention the port to use. For example:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database');
So, to connect with a manager that doesn't use port 3306, you have to specify the port number on the connection request:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database', '3307');
To check the connections on the MySQL or MariaDB database manager, use the script:
wamp(64)\www\testmysql.php
by putting 'http://localhost/testmysql.php' in the browser address bar having first modified the script according to your parameters.
I forgot to start the service so it failed because no service was listening on port.
Resolved by starting the service.

tcl close does not gracefully terminate tcp/ip connection

In tcl (tcl 8.4 or 8.6 on Windows), closing a socket connection does not seem to terminate the underlying TCP/IP connection gracefully.
The code below shows a simple time server and associated client. Upon connection from the client, the server sends the current time and server uptime, then closes the connection. The client also closes its side after reading the response from the server. However the underlying tcp/ip connection lingers as a zombie connection in "TIME WAIT" state for 30 seconds before it times out.
Once a few thousands of these zombie connections concurrently exist, the code ends up crashing with an "unable to connect to the server" message or the likes.
Is there a way I can prevent this and gracefully terminate the underlying tcp/ip connection?
#server
proc Server {startTime channel clientaddr clientport} {
puts "Connection from $clientaddr registered"
set now [clock seconds]
puts $channel [clock format $now]
puts $channel "[expr {$now - $startTime}] since start"
close $channel
}
socket -server [list Server [clock seconds]] 9900
vwait forever
#client
set server "127.0.0.1"
set sockChan [socket $server 9900]
gets $sockChan line1
gets $sockChan line2
close $sockChan
puts "The time on $server is $line1"
puts "That is [lindex $line2 0]s since the server started"
Output from currport (zombie connection)
==================================================
Process Name : Unknown
Process ID : 0
Protocol : TCP
Local Port : 9900
Local Port Name :
Local Address : 127.0.0.1
Remote Port : 27524
Remote Port Name :
Remote Address : 127.0.0.1
Remote Host Name :
State : Time Wait
Well reproduced now: flood with lot of sockets in TIME_WAIT is good observable, almost for every socket (if opened and closed immediately).
Normally it does exactly the opposite, so per default after closesocket Windows executes "graceful shutdown" (in order to enable queued data to be sent), but for some reasons lindering causes such flooding with "half" closed or opened sockets for a long time, despite there is nothing to send (excepting possibly a notifying packet "socket going closed").
I investigated a bit (is quite strange) and opened a ticket in tcl-core now
[b6d0d8cc2c].
I'll try to provide some solution for that.
Thank you for notifying us.

Actionscript ServerSocket Verify Connection

In flash, we can create a server socket with this:
protected var socket:ServerSocket = new ServerSocket();
protected function createServer():void
{
socket.bind(1234,"0.0.0.0");
socket.addEventListener(ServerSocketConnectEvent.CONNECT, clientConnectedHandler);
// start listening for connections
socket.listen();
}
With this, any flash application try to connect to the server socket with the port 1234 will get connected. How can I do verification on connection to make sure it is connected from my application before accepting the connection on server socket?
Thank you.
SockerServer instance will throw errors on failure:
RangeError — This error occurs when localPort is less than 0 or greater than 65535.
ArgumentError — This error occurs when localAddress is not a
syntactically well-formed IP address. IOError — when the socket
cannot be bound, such as when: the underlying network socket (IP and
port) is already in bound by another object or process. the
application is running under a user account that does not have the
privileges necessary to bind to the port. Privilege issues typically
occur when attempting to bind to well known ports (localPort < 1024)
this ServerSocket object is already bound. (Call close() before
binding to a different socket.) when localAddress is not a valid local
address.
You can use try..catch statements to handle those errors.
If those errors aren't thrown, opening port went successfully :)

Can't connect to MySQL server on 'localhost' (10055)

I am running three perl scripts sequentially. Each of them connects to a Mysql database multiple times, and either selects or updates the information contained in the database. After running these three scripts about 20~ times (& connecting/disconnecting from database many more times than this), I get the message 'Can't connect to MySQL server on 'localhost' (10055).
I have read elsewhere that I could get it to reconnect to the database using mysql_auto_reconnect=1, however I'm not entirely sure that that is the problem. The Mysql server on my computer is still connected when the program crashes - I don't have to restart it. I wanted to understand why it is doing this, and also I'm not entirely sure how I put in '"mysql_auto_reconnect=1", as when I do this it tells me DBI->connect using old style syntax is deprecated.
my $dbh_m= DBI->connect("dbi:mysql:XXX","root","XXX","mysql_auto_reconnect=1")
or die("Error at select Trans: $DBI::errstr");
Do I also need to write this in every time I connect to the database? (Putting that into one of the connections doesn't solve the problem, I still get error messages from all the others - it doesn't begin to run again and then re-crash later). Is this a problem with me connecting/disconnecting to the database to many times?
Thank you!
DBI->connect("dbi:mysql:XXX", "root", "XXX", { mysql_auto_reconnect => 1 })
What error message do you get?
You should probably do something like:
my $dbh;
{
local $#;
do {
eval {
$dbh = DBI->connect("dbi:mysql:XXX", "root", "XXX", { mysql_auto_reconnect => 1 })
};
if ( $# ) {
warn "Error: $DBI::errstr\n";
warn "Trying to reconnect in 5 sec.\n";
sleep 5;
}
} while ($#);
}
Just in case that the database is not responding or there are too many connections.
Maybe you are not disconnecting from the mysql when your script finishes?
It is eat up resources in mysql. Please, check mysql logs for clue.
Regards,
How to Fix MySQL Error 10055
To fix the problem you need to increase the number of dynamic ports.
Running the following Commands will give give you 50000 ports for dynamic use.
On Windows Server 2008 R2
Open command Prompt
Type the following
netsh int ipv4 set dynamicport tcp start=10000 num=50000
Press Enter
Type the following
netsh int ipv4 set dynamicport udp start=10000 num=50000
Press Enter
Type the following
netsh int ipv6 set dynamicport tcp start=10000 num=50000
Press Enter
Type the following
netsh int ipv6 set dynamicport udp start=10000 num=50000
Press Enter

Continuous email server Connection using JAVA Mail API

We are intended to develop a service, which always stay connected to email server, so that whenever a user triggers a mail, it will sent by using the connect instead of getting a new connection and sending the mail.
Is is possible that we always stay connection to email server using JAVA Mail API??.
kindly help me in this.
When you connect to SMTP server (also when using javax.mail API), you use a socket connection (see the src of SMTPTransport and Transport classes). Sockets let you connect to a remote server and that connection remains open until explicitly closed. This means that theoreticaly you could create a connection and them reuse it.
However, many SMTP servers are pretty evil and will kill the connection if you are using it "too slow" or if you try to resuse your SMTP session to often. (I looked up postfix settings for you.)
The Java Mail API allows you to create the connection and close it whenever you want to. Smth. like this:
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(msg, addressArray);
// you can do transport.close(); later
However, because of the fact how the SMTP servers are, you can't just execute connect() once and forget it. At most, what you can do, is properly handle forced disconnects by reconnecting again. There is a notification mechanism in the Java Mail API to do that (take a look at the usage of the notifyConnectionListeners method)
However, because of the fact how the SMTP servers are, you can't just
execute connect() once and forget it. At most, what you can do, is
properly handle forced disconnects by reconnecting again.
Agreed!
You can in fact reuse the JavaMail SMTP connection with below logic:
Transport transport = null;
MimeMessage message = null;
Properties prop = new Properties();
// load all smtp properties
Session session = Session.getDefaultInstance(prop, null);
transport = session.getTransport("smtp");
for (EachMail eachMail : list) {
if (!transport.isConnected()) {
if (port != null && port.length() > 0) {
transport.connect(host, Integer.parseInt(port), "<username>", "<password>");
} else {
transport.connect(host, "<username>", "<password>");
}
}
// set all mail attributes from eachMail object
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
}
Works like a charm. Cheers!
If you want an always up connection you should create your Transport outside of the sending method, but to avoid excpetions on sending (SMTPSendFailedException 421 Timeout data client) you should check if the transport is connected, and if not to connect it again befor sending:
if (!transport.isConnected())//make sure the connection is alive
transport.connect();
transport.sendMessage(message, message.getAllRecipients());