简体   繁体   中英

C# write image to TCP socket

I have the following code that saves an image from a camera to disk:

public static Image getAndSaveImage(int imageCount)
{
    var image = _camera.GetImage() as ThermalImage;
    image.Palette = PaletteManager.Iron;
    _camera.GetImage().EnterLock();
    Image camImage = _camera.GetImage().Image;
    _camera.GetImage().ExitLock();
    camImage.Save("./images/picture" + Convert.ToString(imageCount) + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
    return camImage;
}

As you see, I am saving the image to a file. Currently, this method is called within a loop. I want to replace the saving to disk with a websocket, so clients can connect to this socket and receive bitmap images from the underlying stream. Since a bitmap is an array, this should work, shouldn't it?
I read at some documentations that I can use the TcpListener class. So I would do the following:

TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);

server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();

How can I write my bitmap image into this stream so a python client on the other side can fetch the images? Do I need to handle the TCP handshakes on my own?

Thanks a lot

Edit: originally, the question asked about WebSocket specifically; everything below is predicated on that - now removed - position.

WebSocket, RFC6455, is not a naked socket - it is a non-trivial frame-based protocol that starts off similarly to HTTP 1.1 before transitioning to a different protocol. So; if you want to use WebSocket, you would probably want to use a web-socket server implementation - doing it by hand is not fun (trust me, I know).

If you want simple, ASP.NET (including ASP.NET Core and Kestrel) has an inbuilt WebSocket API, trivially googlable.

However! Because it is a frame-based protocol, you won't be using a regular Stream . WebSocket has 2 main data frame types: text and binary (if we ignore the early prototypes of WebSocket that only had text, and was fundamentally a different protocol that shaded a name) - in your case you'll want binary, obviously, and your best bet is probably to change your existing code to save to a MemoryStream , then get the buffer from the MemoryStream to pass to the WebSocket API. The simplest approach there is ToArray() on the MemoryStream , but the more efficient approach is to use GetBuffer() or TryGetBuffer() , and use an API that accepts an oversized buffer with offset (usually 0) and length (which will be (int)memoryStream.Length ).

If you don't actually mean WebSocket, but you just mean "a TCP socket, accessed over the internet", then ignore everything I've said; TcpListener should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM