IPv6 socket works in Mono console app but not Unity app - c#

I have a problem with some code that uses sockets. I want to connect my script over IPv6 but I receive a SocketException when I run this script in Unity. This code works perfectly as a Console Application Project in MonoDevelop:
using System;
using System.Net;
using System.Net.Sockets;
namespace socketIPv6
{
class MainClass
{
public static void Main (string[] args)
{
Socket s;
s = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse("ff15::2");
s.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(ip));
IPEndPoint ipep = new IPEndPoint(IPAddress.IPv6Any, 26000);
s.Bind(ipep);
while (true) {
byte[] b = new byte[1024];
s.Receive (b);
string str = System.Text.Encoding.ASCII.GetString (b, 0, b.Length);
Console.WriteLine (str.Trim ());
}
}
}
}
But the same code (I only changed "Console.WriteLine()" for "Debug.Log()") doesn't work as a Unity Project. This code breaks with the exception: "SocketException: An address incompatible with the requested protocol was used." Can someone help me? Thanks!

Keep in mind that the version of the Mono framework you're linking against from a console app may be different than Unity's mono framework.
This may partially answer what's going on:
Decompiling Unity\Editor\Data\Mono\lib\mono\2.0\System.dll with ILSpy shows at various places a dependency on
internal static void Socket.CheckProtocolSupport()
which, among one other related check therein, attempts to read from the .NET config file(s) from section system.net/settings. If you look at Unity\Editor\Data\Mono\etc\mono\2.0\machine.config it has system.net/settings/<ipv6 enabled="false"/>.
So either that config file is irrelevant or stale, or it appears Unity specifically has turned off or does not support IPv6 sockets.

Try using the ".Net 2.0 Subset" api compatibility in the player settings. I was running in this same thing and it was because we were using the full ".Net 2.0"
This is the bug report if you're interested: https://fogbugz.unity3d.com/default.asp?804510_c5ei44diq6ktnh1u

Related

Can't connect a midi output device to .net MAUI using DryWetMidi

I am using the library DryWetMIDI for .net 7 and I am trying to connect a MIDI output device to MAUI. When I connect a input device it seems to work fine but the only output from the outputdevice I could get was the following error: Internal error (OUT_SENDSHORTRESULT_INVALIDHANDLE). When I tried everything in a simple console application it works perfectly.
Also because of my lack in experience in Maui I don’t really know if I should change something in the project dependencies or in the builder. Or maybe declare the MIDI in the App or the Appshell...
So I tried to create a input device and a output device and connect them to eachother (This is what the DryWetMIDI suggested). Next I try to get the events from the input and the outup device, the input device works but the output device doesnt.
I use the following code where the ouput device doesnt work in Maui:
private InputDevice inputDevice;
private OutputDevice outputDevice;
private DevicesConnector devicesConnector;
void ConnectMidi()
{
//create input device
inputDevice = InputDevice.GetByName("Keystation Mini 32");
inputDevice.EventReceived += OnEventReceived;
//create ouput device;
outputDevice = OutputDevice.GetByName("Microsoft GS Wavetable Synth");
outputDevice.EventSent += OnEventSent;
//connect them
devicesConnector = inputDevice.Connect(outputDevice);
inputDevice.StartEventsListening();
}
public void OnEventReceived(object sender, MidiEventReceivedEventArgs e)
{
var midiDevice = (MidiDevice)sender;
Debug.WriteLine("This gets called when a key is pressed") ;
}
public void OnEventSent(object sender, MidiEventReceivedEventArgs e)
{
var midiDevice = (MidiDevice)sender;
Debug.WriteLine("This gets never called");
}
If there is anohter solution using a diffrent library or something else I would love to hear it!
Hopefully this makes my problem clear and thanks in advance.
(This is also my first post so feedback would also be nice)
I'm the author of the DryWetMIDI. I've analyzed the problem:
The bug is not with the library, it's a MAUI related one.
The error comes from midiOutOpen system Windows function which fails for Microsoft GS Wavetable Synth in a MAUI project but works for any other project types.
I've reported the bug in MAUI repo: https://github.com/dotnet/maui/issues/12368. So what we have is to wait for response from Microsoft.
Update:
The bug has been moved to WinUI repo: https://github.com/microsoft/microsoft-ui-xaml/issues/8055. Also you can mark your project as Unpackaged and the issue should go away.

Sending data from the Flutter web app to my local server is not working

I am a beginner with Dart and Flutter. I'm trying to learn to work with WebSocket.
I want to send data to my local server that I created by C# language.
My Flutter web app will connect to the server but it will never send any data.
Here is my Flutter source code:
import 'package:web_socket_channel/web_socket_channel.dart';
void main(List<String> arguments) async {
final WebSocketChannel channel =
WebSocketChannel.connect(Uri.parse('wss://127.0.0.1:4444'));
channel.sink.add('It is working!');
}
And it's my C# source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 4444);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:4444.{0}Waiting for a connection...", Environment.NewLine);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
while (true)
{
while (!stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
String text = Encoding.UTF8.GetString(bytes);
Console.WriteLine(text);
}
}
}
}
Finally, my console application result after running my Flutter web app:
Click Here To See The Image
I got no errors and I think my web app connected to my local server correctly, didn't it? But still can't send any data.
I have two questions:
1)How can I send data to my local server correctly?
2)Why did appear some strange characters in my console application after my web app has connected?
Thanks to you so much for answering my questions.

Does anyone know where I can find a Universal Windows Private Network (Client & Server) code Example?

I am brand new to Universal Windows Apps (Win 10). I am trying to port a console application over to UWP that acts as a remote testing and administrative console for a custom Windows Service application. I can not seem to find any solid example code to demonstrate where to place a socket listener in the MainPage.xaml.cs file (or wherever it's supposed to go). I have been successful with porting the MSDN example into a method that serializes a PCL model object with Json and sends it to the server. I just can not seem to handle the listener correctly. I don't think that I am using it in the right place, especially when it comes to the async usage. I am having protocol\port usage errors because it's basically saying that it is already open (I just tossed it in the test method). I would like to deserialize the Json response that is received and use it to populate a List. Here is an example of what is working for me for sending.
private async void Pulse(string target)
{
if (target == null || target == string.Empty)
{
greetingOutput.Text = "No Ip specified";
return;
}
else
{
try
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName(target);
await socket.ConnectAsync(serverHost, serverPort);
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
HeartBeatPing heartBeatPing = new HeartBeatPing(GetLocalIp(), target);
string msg = JsonConvert.SerializeObject(heartBeatPing);
await writer.WriteLineAsync(msg);
await writer.FlushAsync();
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch (Exception xCeption)
{
greetingOutput.Text += "\n" + xCeption.ToString();
}
}
}
Some of you might notice from the greetingsOutput.text that I have started with the "C# Hello World" example from Microsoft's training site.
I would also like to add that I am not going to be using any HTTP for this because there is going to be some custom encryption and other "things" happening with the Json objects that will require separate ports.
I'm not far enough into my Universal Windows Apps with XAML and C# (Unleashed) books to have even a clue as to what I am doing. I am however well seasoned C# programmer in other platforms such as MVC, Windows Service, Console, and others. I have a solid understand of enterprise class patterns and practices based on my knowledge of "The Gang of Four".
Any help would be greatly appreciated. Thank you.
(https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DatagramSocket)
Here is a sample. There are CPP, js, and cs code in this sample, I've only tested the cs code. Wish this can help you.

Can't get cached items back from memcached?

I just setup memcached on a ubuntu system i have on my network. Didn't change any options so everything is default. I think tried to connect to the server using Enyim. It doesn't fail but when i try to retrieve the items they are always null. I'm not much of a low level won't but i've been able to discern things from wireshark before so i decided to give it a try. I'haven't been able to discern anything but i noticed the first .Store() command i sent actually sent network packets to the correct address. Every .Store() command did absolutely nothing.
Here is my app.config:
I've tried both "Binary" & "Text" Protocols and they did the same thing.
Here is my c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
namespace MemCacheTest
{
internal class Program
{
private static void Main(string[] args)
{
//var config = new MemcachedClientConfiguration();
//config.Servers.Add(new IPEndPoint(new IPAddress(new byte[] {10, 0, 0, 1}), 11211));
//config.Protocol = MemcachedProtocol.Binary;
var mc = new MemcachedClient();
for (var i = 0; i < 100; i++)
mc.Store(StoreMode.Set, "Hello", "World");
mc.Store(StoreMode.Set, "MyKey", "Hello World");
Console.WriteLine(mc.Get("MyKey"));
Console.WriteLine("It should have failed!!!");
Console.ReadLine();
}
}
}
Does anyone know whats going on or how i could determine what is wrong? I thought it was strange that i wasn't getting any exceptions so i set an invalid ip address in the config file. Same results.
The short answer: If your service is running check your port, it should be blocked somehow. (did you add an exception for port 11211 in Ubuntu firewall(iptables)?)
telnet 10.0.0.1 11211 If you have a telnet client on your server this will show the port is inaccessible.
Enyim doesn't throw you an error even the port is inaccessible. yes, it's strange.
To add to dasun answer. When you install memcached by default its configured to only listen on the "lo/localhost" interface. Its the only security memcache really has. Even if you try to telnet locally and do specify the lo interface for example:
telnet 10.0.0.1 11211
it will fail. To fix you have to go into the memcached.conf file and comment out
# -l 127.0.0.1
and then restart the service

Using Sockets to transfer Data with MonoDroid

I'm trying to send some information to a server with Android using Monodroid.
The code is as follows:
public void sendSomething()
{
sock = new TcpClient();
sock.Connect(Dns.GetHostAddresses("a.domain.com"), 7777);
String d;
d = "somedata";
StreamWriter w = new StreamWriter(sock.GetStream());
// StreamReader r = new StreamReader(sock.GetStream());
w.WriteLine(d);
w.Flush();
sock.Close();
}
It works fine if I run the exact same routine in a winforms application, but when linked to a button click in monodroid (running on the android virtual device - I'm using the evaluation version) the server will see the connection but no data is received.
Does anybody have any idea why this could be?
(edited to ammend code)
It could be a server issue. E.g. let's assume that:
a) your winform app running on Windows / MS.NET (and not on Mono / Linux or OSX);
b) your server is Windows-based too and does a ReadLine to read sockets
Then the NewLine between the write (Unix \n) and the read (Windows \r\n\) could explain why the server does not report what's being read.
Can you show us how you're reading the data on the server ? (edit your question)

Categories

Resources