Bluetooth Server Socket on Unity3d - c#

I currently have client socket code on visual studio written in c++ that creates a Bluetooth client socket. Previously, I had written code in Java for a Bluetooth server socket and everything was working, but I want to have the server socket on unity so that I can receive data into the Unity application to perform a function. I decided to rewrite the server socket code in C# to use in unity and am using the InTheHand.dll library. Is this doable in Unity? I don't have pro but I understand net libraries can be used in the free version. I am receiving a lot of errors but I am unsure if it is because what I am trying to do is not possible with the free version of Unity or if I'm doing it wrong. Here is the piece of my Code where I try to make the Bluetooth server socket in unity. I have "using InTheHand.Net" and a couple of other includes for the other Bluetooth functionalities :
Guid UUID = new Guid("0000-1000-8000-00805F9B34FB");
bool ServerRunning = false;
Stream mStream;
BluetoothListener BTListener = new BluetoothListener(UUID);
BTListener.Start();
ServerRunning = true;
BluetoothClient conn = BTListener.AcceptBluetoothClient();
mStream = conn.GetStream()

Related

UdpClient does not receive any data in UWP app

I have a UWP app that needs to use UdpClient to receive some data. The code looks very similar to this:
var udp = new UdpClient(port);
var groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
Trace.WriteLine("Waiting for broadcast");
byte[] bytes = udp.Receive(ref groupEP);
Trace.WriteLine($"Received broadcast from {groupEP} :");
Trace.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
When I run this code in UWP app it stops at Receive(), does not receive anything, and there are no exceptions.
If I run the same exact code in NET 5 console app everything works fine.
How can I make this code run in UWP app?
A common reason for such kind of network issue is the local network loopback. UWP apps are running in the sandbox and are isolated from the system resources like network and file system. In other works, UWP apps are not allowed to access the local host address by default. Enabling the local network loopback could make UWP apps able to access local network resources.
Please also make sure that you've enabled the enterpriseAuthentication and privateNetworkClientServer capability in the manifest file.

nodejs Net socket client communication with c# .net server application

I have a C# .net server service application which listens on port 11111 for a connection. I have tested it with another c# test application which can send and recieve communication for and from the server.
Now the production scenario is that this C# .net server application is to recieve connection from, amongst others, a nodejs client which is encapsulated in Electron. So i create this function in NodeJS
const net = require( "net");
const socket = new net.Socket();
socket.connect('11111','127.0.0.1');
exports.socket = socket;
I import it in the IPC layer of Electron.
const { socket } = require("./socketInit.js");
and when doing that i get this error
A JavaScript error occurred in the browser process
Error: connect ECONNREFUSED 127.0.0.1:11111
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
It wont connect to the server socket.
Im not even using the socket yet, but i understand that the connection attempt is doing the handshake and that must be where the error happens.
Does anyone have any idea what could be wrong ?
TY for your time!
Im quite sure it is because the code is in a renderpass which runs several times, and then the code in reality tries to open a connection on a port where a connection is already open each time there is a renderpass except from the first.
I destroyed the connection after sending and now i dont get the error anymore. But im not getting any data send to the server, but that is for another question.
I'm integrating this into an existing codebase, which i don't fully understand as im a total newb to NodeJS, Javascript and Electron, so im not sure how it all works :)

play audio from TCP/IP server in UWP client on PI3

I'm trying to make an uwp app which will be a client and will run on PI3. The server is a C# Winforms app, that runs on my Windows 10 computer, which I've found here: https://www.codeproject.com/Articles/482735/TCP-Audio-Streamer-and-Player-Voice-Chat-over-IP. The server can stream audio from microphone device to all the connected clients. Although the project has its own client and I can run both server and client on my local machine. Now I want to build a similar client app in UWP C#. By using the UWP StreamSocketActivity sample, I can connect to the server. But I don't know how to receive the audio data and play it on UWP client. Could anyone give me a hand?
Blow is the screenshot of running server which has one connection from uwp client:
Client connects to the server
Thanks in advance!
As mentioned in the article, the protocol used to transfer the audio data is customized.
Note !!! This is a proprietary project. You can't use my servers or
clients with any other standardized servers or clients. I don't use
standards like RTCP or SDP.
You can find the code in TcpProtocols.cs. In UWP client app, you need to convert the code for UWP. This document shows how to build a basic TCP socket client in UWP. But you also need to modify the code for receive data from server continuously. Following code may be helpful for you.
private async void StartClient()
{
try
{
// Create the StreamSocket and establish a connection to the echo server.
using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
{
// The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
var hostName = new Windows.Networking.HostName(TxtHostName.Text);
await streamSocket.ConnectAsync(hostName, TxtPortNumber.Text);
while(true)
{
using (var reader = new DataReader(streamSocket.InputStream))
{
reader.InputStreamOptions = InputStreamOptions.Partial;
uint numAudioBytes = await reader.LoadAsync(reader.UnconsumedBufferLength);
byte[] audioBytes = new byte[numAudioBytes];
reader.ReadBytes(audioBytes);
//Parse data to RTP packet
audioBytes = Convert_Protocol_LH(audioBytes);
var pcmStream = audioBytes.AsBuffer().AsStream().AsRandomAccessStream();
MediaElementForAudio.SetSource(pcmStream, "audio/x-wav");
MediaElementForAudio.Play();
}
}
}
}
catch (Exception ex)
{
Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
}
}
UPDATE:
RTP Packet
RTSP for living audio is recommended and wide used.The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming media servers. The protocol is used for establishing and controlling media sessions between end points. There are some advantages of RTSP. In this solution, you need to build a RTSP server and then use VLC.MediaElement library or other library which support on Windows IoT Core in your UWP app. But i am not sure this library supports RTP.
In addition, this document shows supported codecs on Windows IoT Core.

Sending message with Router-Dealer Proxy using c# and python

I am able to have c# (client) and python (server) talk to each other by using a simple request-reply. However, I want my web application built on c# asp.net to be stable and need more clients and servers, so I tried connecting c# and python using the Router-Dealer Proxy with python.
I tried running the proxy python script first, then running c# (client), then python (server). However, when I run the python (server), it gives me an "Address in use" error message.
Am I running them in a wrong order OR is there something wrong with the proxy python script (shown below)?
5602 = c# client
5603 = python server
def main():
context = zmq.Context()
# Socket facing clients
frontend = context.socket(zmq.ROUTER)
frontend.bind("tcp://*:5602")
# Socket facing services
backend = context.socket(zmq.DEALER)
backend.bind("tcp://*:5603")
zmq.proxy(frontend, backend)
# We never get hereā€¦
frontend.close()
backend.close()
context.term()
if __name__ == "__main__":
main()
I'm assuming your servers use bind, so the proxy should connect to them rather than also using bind.
Note: in zeromq the order of application startup doesn't matter so you can tell your proxy to connect to a server that doesn't yet exist, when the server is started the connection will be made.

Stomp WebSocket Client for a Spring based broker built in Java is failing

I have a Websocket Stomp server built in Java (Spring based). My JavaScript client is able to talk to the server using Stomp over Web Socket - no issues.
I'm trying to use the WebSocket4Net library to build the C# client. Can anyone please tell me how can I build the Stomp message frames in bytes[] and send them to the server?
In the OnOpen() method, I'm doing the following:
String stompMsg = "CONNECT\n";
stompMsg += "accept-version:1.1,1.2\n\n";
stompMsg += "^#";
Byte[] bytesToSend = Encoding.UTF8.GetBytes(stompMsg);
websocketObj.Send(bytesToSend, 0, bytesToSend.Length);
I get the following message from server:
Failed to parse BinaryMessage payload - java.nio.HeapByteBuffer.
Sending STOMP ERROR to client.
java.lang.IllegalArgumentException: Object of class [org.springframework.web.socket.BinaryMessage] must be an instance of class org.springframework.web.socket.TextMessage
at org.springframework.util.Assert.isInstanceOf(Assert.java:339)
at org.springframework.util.Assert.isInstanceOf(Assert.java:319)
at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:189)
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:307)
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75)
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:55)
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:71)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleBinaryMessage(StandardWebSocketHandlerAdapter.java:122)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$100(StandardWebSocketHandlerAdapter.java:42)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$4.onMessage(StandardWebSocketHandlerAdapter.java:88)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$4.onMessage(StandardWebSocketHandlerAdapter.java:85)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageBinary(WsFrameBase.java:549)
at org.apache.tomcat.websocket.WsFrameBase.processDataBinary(WsFrameBase.java:514)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:274)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:116)
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:54)
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192)
at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:178)
at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:92)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:601)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2430)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2419)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Can anyone please suggest if you have successfully created / used any C# client library with a spring based STOMP over Web Socket server?
#Artem - Thank you SO much. The \0 indeed did the trick.
websocket.Send("SUBSCRIBE\nid:sub-0\ndestination:/topic/mytopic\n\n\0");

Categories

Resources