Can I connect to local windows service application (c#) with secure WebSocket (wss)
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
i solve
X509Certificate oCertificate = CertificateKontrol.GetCertificate();
public class CertificateKontrol
{
public static X509Certificate2 GetCertificate()
{
try
{
byte[] barySertifika = global::EImzaAt.Properties.Resources.cert;
using (Stream stream = new MemoryStream(barySertifika))
{
return new X509Certificate2(ReadStream(stream), pwd);
}
}
catch (System.Exception ex)
{
throw new System.Exception("err");
}
}
private static byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
Related
I'm trying to send recordRTC blob via websocket to my Java server, my goal is to build a video stream service.
However, when the server received the blob, and write file, the web page would refresh, cause recordRTC stopped and socket disconnct.
Used package
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.4.0</version>
</dependency>
The following is my code.
Server side
public void onMessage( WebSocket conn, ByteBuffer message ) {
byte[] bytes = new byte[message.remaining()];
message.get(bytes, 0, bytes.length);
if(bytes.length > 0) {
OutputStream os = null;
UUID uuid = UUID.randomUUID();
String id=uuid.toString();
String filename =id.replace("-", "");
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(
new File("./uploads/"+filename +".webm")));
bos.write(bytes);
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client side
function startCapture() {
logElem.innerHTML = "";
try {
videoElem.srcObject = navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then(
(stream)=>{
console.log(stream);
recordRTC = RecordRTC(stream);
recordRTC.startRecording();
// blob segment and send every 3 second
recording = setInterval(()=>{
recordRTC.stopRecording(()=>{
console.log("BLOB : ", recordRTC.getBlob());
recordRTC.getBlob().arrayBuffer().then((val)=>{
console.log("BLOB : ", recordRTC.getBlob());
socket.send(val);
});
})
recordRTC.startRecording();
}, 3000);
videoElem.srcObject = new MediaStream(stream);
});
} catch (err) {
console.error("Error: " + err);
}
}
reload event picture
I found the reload EVENT occur after the fisrt blob sent and write to file, but I don't know why the event happend.
If server don't write blob to file, just receive it, the websocket and web would work perfectly without reloading.
How could I solve the reload EVENT problem?
Thanks
I have a project in NativeScript and i'm accessing the bluetooth android api via JavaScript as in this example:
android.bluetooth.BluetoothAdapter.getDefaultAdapter();
I am able to find the paired devices and connect to them. I wanted some example of how to forward data to the device and have a return of this device.
I've seen something in the android documents about:
getOutputStream()
and
getInputStream()
but I do not know how to use this via JavaScript.
I want is to send an command to an Elm327 OBD2 device and receive the data from this device.
Sample native code:
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
So I'm trying to make a webservice that allows someone to obtain data from a server. Right now, the server I'm using is written using java's HttpServer class. I plan to make the server accessible using fetch() in javascript, but it's not working.
When I was first testing out my server, I used Apache's HttpComponents library, and that client(written in java). was able to receive the test json that came from my server. However, when I used fetch() on my javascript client, nothing is received when I console.log everything. It doesn't make sense to me why it would work in Java, but not javascript. Does anyone know why this is not working? Am I just doing the javascript part wrong, and it does actually work? Thanks!
Code snippets for reference:
java server:
public class Main {
private static final int PORT = 1337;
private static final int BACKLOG = 1;
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), BACKLOG);
System.out.print("started on" + PORT);
HttpContext context = server.createContext("/ex", new Handler());
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Handler implements HttpHandler {
#Override
public void handle(HttpExchange he) throws IOException {
System.out.println("handled");
JSONObject obj = new JSONObject();
obj.put("name", "value");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
obj.put("array", new int[]{1, 2, 3});
String response = obj.toJSONString();
he.sendResponseHeaders(200, response.length());
he.getResponseBody().write(response.getBytes());
}
}
java client:
public class PostTest {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:1337/ex");
CloseableHttpResponse response = httpClient.execute(httppost);
System.out.println("STATUS LINE");
System.out.println(response.getStatusLine().toString());
System.out.println("HEADER");
Header[] h = response.getAllHeaders();
for(int i = 0; i < h.length; i++) {
System.out.println(h[i]);
}
System.out.println("ENTITY.CONTENT");
try(BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"))) {
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
}
}
}
Javascript:
var init = {mode: "no-cors"};
async function f() {
return fetch("http://localhost:1337/ex", init).then(res => res.text()).then(posts => console.log(posts));
}
f();
I'm trying to send binary data between server (C#) application and client (js-application -- made by WebSocket). Connection between server and client is established and handshake is OK. Messages from client are receiving by server, but when I'm trying to send binary data to client, the event "onmessage" doesn't work.
This is fragments of my C# code. Sending binary data in "sendFile" function.
class Listener
{
private IPAddress ip;
private int port;
private TcpListener server;
private TcpClient client;
private NetworkStream stream;
private bool isSuccHandshaked;
public Listener()
{
ip = IPAddress.Loopback;
port = 8080;
server = new TcpListener(ip, port);
isSuccHandshaked = false;
}
private void makeHandshake()
{
//...
}
private String decodeMessage(Byte[] bytes)
{
//...
}
private void sendFile()
{
Byte[] dataToSend = File.ReadAllBytes("test.txt");
stream.Write(datatosend, 0, datatosend.Length);
stream.Flush();
}
public void startListen()
{
server.Start();
Console.WriteLine("Server has started on {0}. Port: {1}. {2}Waiting for a connection...", ip, port, Environment.NewLine);
client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
stream = client.GetStream();
while (!isSuccHandshaked)
{
makeHandshake();
}
while (true)
{
if (client.Available > 0)
{
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
String message = decodeMessage(bytes);
sendFile();
}
}
}
}
}
and js-code:
var address = 'ws://localhost:8080';
var socket = new WebSocket( address );
socket.binaryType = "arraybuffer";
socket.onopen = function () {
alert( 'handshake successfully established. May send data now...' );
socket.send( "Aff" );
};
socket.onclose = function () {
alert( 'connection closed' );
};
socket.onmessage = function ( evt ) {
console.log( "Receive message!" );
console.log( "Got ws message: " + evt.data );
}
Maybe there is some peculiar properties in receiving data with WebSocket protocol? Wich useful approaches to send binary data from C# code to js you can recommend?
A websocket is not a raw TCP socket. It uses HTTP negotiation and its own framing protocol you have to comply with. If you are interested in writing your own server in C# take a look at this.
However if you only want to use them, you can either use the default Microsoft implementation with IIS, or you can use one of the many standalone websockets components. I maintain one named WebSocketListener.
Is it possible to allow people to upload videos on my Youtube channel to my website authentication in asp.net ?
or
upload video in one youtube channel. different dieferent authentication but channel is same
The code sample below calls the API's videos.insert method to upload a video to the channel associated with the request. for more details go through this click here
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: upload a video.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted
/// </summary>
internal class UploadVideo
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = #"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}