I have problem with receiving an image over TCP socket [.net 4.0]
Server:
Socket s = null;
Socket client;
private void button1_Click(object sender, EventArgs e)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, 9988));
s.Listen(1);
client = s.Accept();
pictureBox1.Image = Image.FromStream(new NetworkStream(client));
//Server freezes here and waiting for the image .. but in the Client side.. it tells that it sent.
Console.WriteLine("Received.");
}
Client:
Socket s = null;
private void button1_Click(object sender, EventArgs e)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9988));
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
bitmap.Save(new NetworkStream(s), ImageFormat.Png);
Console.WriteLine("sent.");
}
Edit:
im making a big application .. image was receiving just fine .. then i did some changes on the code so it got complicated to know what did i exactly change .. now it’s not working .. so i made new projects and tried the code up.. still doesn’t work .. i know that there’s another ways to do it.. but i prefer to do this way.
Anyone knows how to fix it ??
Most probably you need to close the socket after sending the data.
Image.FromStream()probably waits until theNetworkStreamindicates there are no more bytes to process, but since you declared theSocketon the form’s class level, it stays connected and the server waits for more data.