Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image.FromStream using networkStream

Tags:

c#

image

sockets

I'm trying to use the method FromStream of the class Image to set an image received by a tcp connection using a network stream. Here there are the two sides code:

Server:

TcpListener server = new TcpListener(IPAddress.Any, 34567);
server.Start();

TcpClient client = server.AcceptTcpClient();
byte[] buffer = new byte[256];

int n = 0;
Console.WriteLine("{0}, {1}", Encoding.ASCII.GetString(buffer, 0, n), client.Client.RemoteEndPoint);
byte[] img = File.ReadAllBytes(@"C:\Users\Luca\Desktop\video grest\8599929-nessun-segnale.jpg");
client.Client.Send(img);

Client:

TcpClient tcp = new TcpClient("127.0.0.1", 34567);
NetworkStream stream = tcp.GetStream();
MessageBox.Show("fatto");
pictureBox1.Image = Image.FromStream(stream);

The problem is that the client program stops on the last instruction and it doesn't go forward, and if close the server (even 30 minutes later) it says the connection was closed but the picturebox doesn't show anything... Why?

Thanks in advance.

like image 272
Covix Avatar asked Dec 29 '25 10:12

Covix


1 Answers

I think that your client code

pictureBox1.Image = Image.FromStream(stream);

is expecting for the stream to be ended before processing the image.

So you should close the socket server-side using:

client.Close();

just after:

client.Client.Send(img);
like image 191
Morix Dev Avatar answered Dec 31 '25 00:12

Morix Dev