我已经使这些代码发送和接收带有TCP套接字的图像,但接收代码不起作用,希望你能帮助我 这是发送代码
public void SendImage()
{
int ScreenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int ScreenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(ScreenWidth, ScreenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(ScreenWidth, ScreenHeight));
bmpScreenShot.Save(Application.StartupPath + "/ScreenShot.jpg", ImageFormat.Jpeg);
byte[] image = new byte[1];
bmpScreenShot = ResizeBitmap(bmpScreenShot, 300, 300);
image = ImageToByte(bmpScreenShot);
//get the length of image (length of bytes)
int NumberOfBytes = image.Length;
//put the size into a byte array
byte[] numberofbytesArray = BitConverter.GetBytes(NumberOfBytes);
//send the size to the Client
int sizesend = sck.Send(numberofbytesArray, 0, numberofbytesArray.Length, 0);
if (sizesend > 0)
{
MessageBox.Show("Size Sent");
}
//send the image to the Client
int imagesend =sck.Send(image, 0, NumberOfBytes, 0);
if (imagesend > 0)
{
MessageBox.Show("Image Sent");
}
}
这是接收代码
public void ReceiveImage()
{
if (sck.Connected)
{
NetworkStream stream = new NetworkStream(sck);
byte[] data = new byte[4];
//Read The Size
stream.Read(data, 0, data.Length);
int size = IPAdress.HostToNetworkOrder(BitConverter.ToInt32(data,0));
// prepare buffer
data = new byte[size];
//Load Image
int read = 0;
while (read != data.Length)
{
read += stream.Read(data, read, data.Length - read);
}
//stream.Read(data, 0, data.Length);
//Convert Image Data To Image
MemoryStream imagestream = new MemoryStream(data);
Bitmap bmp = new Bitmap(imagestream);
pictureBox1.Image = bmp;
}
}
修改 将IPAdress.HostToNetworkOrder移除到以下
后int size = BitConverter.ToInt32(data,0);
还有一个问题。问题是当我发送大小时,它被发送为5kb,但是当我收到它时,我发现它接近2GB。
此外,我在此行收到错误
read += stream.Read(data, read, data.Length - read);
使用以下消息
无法从传输连接中读取数据。可以执行套接字上的操作,因为系统缺少足够的缓冲区空间或者队列已满。
答案 0 :(得分:1)
除非您创建的服务器应该与java服务器/客户端兼容,否则请勿使用HostToNetwork订单。如果这样做,您还需要更改要发送的int数据缓冲区的顺序。
您也可以直接将客户端上接收的字节写入内存流,而不是分配数据并将字节写入内存流。还有一个重要的注意事项,在将它移交给位图构造函数之前,不要忘记设置imagestream.Position = 0
。