Is it possible to send messages over UDP/TCP from flutter application to .NET application? - flutter

I am trying to figure out how to send data over UDP/TCP from my flutter application to my server which has .net applications which listen for UDP and TCP . I searched about it and I found that there is a package named web_socket_channel and I tried that it is working with the testing server ws://echo.websocket.org but when I replace the echo.websocket.org with my server IP address or domain name it doesn't work even i am not getting any errors back so I couldn't figure out what's going on. Is there something wrong? or am i doing something wrong? Can someone help me with my demo code :
WebSocketChannel channel;
String text = "";
void sendSocket() {
String message = "message_text"
if(message.isNotEmpty)
channel.sink.add(message);
}
getStreamData() {
channel.stream.asBroadcastStream().listen((event) {
if (event != null)
print(event);
});
}
#override
void dispose() {
channel.sink.close();
super.dispose();
}
#override
void initState() {
try {
channel = IOWebSocketChannel.connect(
'ws://127.0.0.1:8889');
getStreamData();
super.initState();
} catch (e) {
print(e.toString());
}
}
I appreciate your help. Thanks you so much.

First, make sure that your server is running and available to connect.
For this problem go through all steps mentioned below:
1. Check your server is running and the app is listening to a specific port on which you are sending data
2. Check the server IP address and Port number
3. Make ping from the command prompt using "ping serverName/IP"
4. Make sure you can connect using telnet from command prompt "telnet serverName/IP portNumber"
(if telnet command doesn't work means your telnet client is not installed/enabled then
check how to enable telnetClient)
1st Solution
if everything works well then try this plugin flutter_socket_plugin or you can write your own code for socket like #Richard Heap suggested.
2nd Solution
Excellent blog on Network Socket Programming for dart: Reference Link
You can also use RawDataGramSocket for the UDP sockets refer to this thread
Socket API for TCP sockets visit this thread

Related

Appwrite sms authentication connection times out

I want to enable phone authentication on my flutter app with appwrite. I followed the official guidelines, changed the .env variables of appwrite and used docker compose up -d to restart appwrite with the correct credentials. As SMS provider I am using text-magic therefore my .env file has the following configurations for sms:
_APP_SMS_PROVIDER=sms://[USERNAME]:[API-KEY]#text-magic
_APP_SMS_FROM=+123456789
Username and API-Key come from textmagic
Additionallly I've created a simple method to create a phone Session.
createPhoneSession(String phonenumber) async {
try {
Client client = Client();
client
.setEndpoint(AppConstants.endpointId)
.setProject(AppConstants.projectId);
Account account = Account(client);
var token = await account.createPhoneSession(userId: ID.unique(), phone: phonenumber);
print(token.$id);
} catch (error) {
print(error);
}
}
The exception I get is the following:
I/flutter ( 5195): AppwriteException: null, Connection timed out (0)
Any suggestions why it keeps timing out? Thank you for your help in advance!
As you mentioned, the endpoint was incorrect. When developing locally, you can't use localhost for the endpoint because the mobile device will try to connect to itself rather than Appwrite. Instead of localhost, you can use your LAN IP.

hololens 2 tcp client - access permissions

I develop for hololens 2 in unity and now got a problem with socket communication.
I am trying to get TCP client on hololens 2 and if I want to connect to TCP server I got the following error on my glasses (in unity it works):
System.Exception: An attempt was made to access a socket in a way forbidden by its access permissions.
I already checked the permissions in Player Settings: InternetClient, InternetClientServer, PrivateNetworkClientServer
Using:
Unity 2019.4.2f1
Api Compatibility Level .NET 4.x
Scripting Backend: IL2CPP
Target SDK Version: 10.0.18362.0
using: Windows.Networking.Sockets.StreamSocket
any suggests?
I faced the connection issue a long time ago while working on Hololens1. I haven't worked on Hololens2 network protocols. But one of the biggest problem I faced was Hololens UWP C# and Unity C# are different from each other and they create a conflict. You may need to specify the directive for the communication. Check out this link. This guys explained the problem and solution really well.
My suggestion is if you are not sending constant requests and periodically sending the data, try creating a server based application which accepts REST API calls. That will be a much robust solution.
I am using Unity 2019.4.13f1 and tcp connection works fine.
Example code:
public string ServerIp = "192.168.31.12";
private const int PORT = 9999;
private Socket Client;
public void CreateClient()
{
Debug.Log("\r\nCreating Client...");
Thread createClientAndConnect = new Thread(() =>
{
try
{
IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse(ServerIp), PORT);
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(serverEP);
Thread listenToServer = new Thread(Receive);
listenToServer.IsBackground = true;
listenToServer.Start(Client);
}
catch (Exception e)
{
Debug.LogError("Error when creating client");
Debug.LogError(e.Message);
}
});
createClientAndConnect.IsBackground = true;
createClientAndConnect.Start();
Debug.Log("Client is created");
}

Testing feathers socket

I have hardly done anything with feathers sockets so far and therefore I need your help.
I have written a test which tests the functionality of my websocket to move users into the right channels. To do this I created two socketIo-clients in my test and let them connect to the websocket with the help of my own helpers, which also do the authentication when the connection is established.
If I run the test on its own, it will work fine. But once I run all the tests together, the test no longer works, because the SocketIo-Clients can not established any connection. This can be noticed, because no connection event is triggered at the server.
In my Test I do:
before((done) => {
server = app.listen(app.get('port'), done);
socketUrl = 'ws://localhost:5555}/';
});
socket = io(socketUrl);
and
after(async () => {
await server.close();
});
I found out, that any test, which is also doing server = app.listen(app.get('port'), done); before the socket test, will cause the socket test to fail. Can it be possible, that await server.close(); does not really close the http-server and/or the ws-server?

Setup a datastreaming server in processing

I want to setup a datastreaming server in Processing, so the Client sends a String to the Server and the Server answeres it. For example Client - Server "Cupcake" then Server - Client "Cupcakce sounds funny" so the Server answeres the string. I tried this with the UDP library and opened the port on the server. But when the server had to answer the Clinet it did'nt work, because I can't open the client's ports. Any solutions?
Sounds like you need two-way communication.
Using UDP you would need two sketches that are both UDP servers and clients.
e.g.
sketch #1 listens on port 12000
sketch #1 sends data on port 12001
sketch #2 listens on port 12001
sketch #2 sends data on port 12000
You can also use TCP sockets.
As the Server you can use Examples > Libraries > Network > ChatServer
I'm surprised there's no ChatClient example, but you can get away with something like this:
import javax.swing.*;
import processing.net.*;
int port = 10002;
Client myClient;
void setup()
{
size(400, 400);
textFont(createFont("SanSerif", 16));
myClient = new Client(this, "localhost", port); // Starts a client on port 10002
background(0);
}
void draw()
{
background(0);
text("client - press ENTER to type\nconnected:"+myClient.active(), 15, 45);
}
void keyReleased() {
if (keyCode == ENTER) {
String message = JOptionPane.showInputDialog(null, "message: ", "TCP Client messaging", JOptionPane.QUESTION_MESSAGE);
println(message);
if (myClient.active() && message != null) {
myClient.write(message);
}
}
}
Note: The server must be running before the client so the client can connect.
Be sure to checkout the difference between UDP and TCP protocols to work out which one makes most sense to use in your case (especially if you pan to use more clients).
Another option worth looking into is WebSockets. This would allow you to have a WebSocket server in Processing and the client could either be another Processing sketch or simply any browser with WebSocket support(e.g. most modern)

Can I set up socket.io chat on heroku?

I have a simple socket.io chat application which I've uploaded to one of the new Heroku 'cedar' stacks.
Now I almost have everything working but I've hit one stumbling block. On my localhost, I open a connection to the socket server from the client with:
// lots of HTML omitted
socket = new io.Socket('localhost', {port: 8888});
But on Heroku, I obviously must substitute something else in for these values.
I can get the port from the process object on the server like so:
port = process.env.PORT || 8888
and pass that to the view.
But what do I substitute for 'localhost'?
The correct way according the article on heroku is:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
socket = new io.Socket();
This ensures that io.Socket won't try to use WebSockets.
I was able to get Socket.IO v0.8 to work on Heroku Cedar by doing the following:
Within the Express app (in CoffeeScript in my case):
app = express.createServer();
socket = require("socket.io")
...
io = socket.listen(app);
io.configure () ->
io.set("transports", ["xhr-polling"])
io.set("polling duration", 10)
io.sockets.on('connection', (socket) ->
socket.on('myaction', (data) ->
...
socket.emit('result', {myData: data})
### The port setting is needed by Heroku or your app won't start
port = process.env.PORT || 3000;
app.listen(port);
And within the front-facing Javascript of your application:
var socket = io.connect(window.location.hostname);
function sendSocketRequest() {
socket.emit('myaction', $("#some_field").val());
}
socket.on('result', function(data) {
console.log(data);
}
Helpful links:
Heroku Node help
Heroku Socket.IO help
This has now changed as of Oct 2013, heroku have added websocket support:
https://devcenter.heroku.com/articles/node-websockets
Use:
heroku labs:enable websockets
To enable websockets and dont forget to remove:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
After trying every combination under the sun I finally just left it blank. Lo and behold that works perfectly. You don't even need the port.
socket = new io.Socket();
I was also having this problem on heroku. I was able to make it work using the hostname "myapp.herokuapp.com" (or simply window.location.hostname, to work both local and in production) and setting the port to 80. I'm using SocketIO 0.6.0.
Wouldn't you just put your actual hostname?
2011-06-25T21:41:31+00:00 heroku[router]: Error H13 (Connection closed without response) -> GET appxxxx.herokuapp.com/socket.io/1/websocket/4fd434d5caad5028b1af690599f4ca8e dyno=web.1 queue= wait= service= status=503 bytes=
Does this maybe mean the heroku router infront of the app is not configured to handle web socket traffic?
[update]
It would appear as of 6/22/2011 the answer is yes... heroku does not support socket.io see this post: http://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities/