Sending/Receiving Image over TCP Socket in C#
I am trying to Send the image to the Client which is connected to my TCP Listner (Server). I am successfully sending and receiving text over Network but I am unable to send the picture to the client from my server. I want to Dislpay the picture in PictureBox placed in the Client Window. Here is a Code I am using to Send and Receive text BUT NOT PICTURE
SERVER:
RECEIVER:
void TListner()
{
try
{
IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
TcpListener tl = new TcpListener(ipendp);
tl.Start();
Socket s1 = tl.AcceptSocket(); ;
NetworkStream ns = new NetworkStream(s1);
StreamReader sr = new StreamReader(ns);
while (true)
{
textBox1.Text = sr.ReadLine();
}
}
catch
{
Application.Exit();
}
}
SENDER:
MemoryStream ms = new MemoryStream();
sw.Write("TEST STRING");
sw.Flush();
CLIENT:
RECEIVER:
void TCP_CLIENT()
{
try
{
IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
TcpClient tcpc = new TcpClient();
tcpc.Connect(ipendp);
NetworkStream ns = tcpc.GetStream();
StreamReader sr = new StreamReader(ns);
while (true)
{
textBox1.Text = sr.ReadLine();
}
}
catch
{
Application.Exit();
}
I want to display the picture开发者_开发知识库 in a PictureBox named PBox1 in Client Window.
You're find to send and receive text because you're using StreamReader
and StreamWriter
. Those deal with text. You haven't actually shown the code you're trying to use for sending pictures, but fundamentally you mustn't use Reader
/Writer
unless you're performing some sort of extra encoding first (e.g. base64).
Also, unless you're going to close the writing socket immediately after sending, you should probably write the data length (e.g. as 4 bytes) before the data so that the receiving socket knows how much it needs to receive.
精彩评论