我已經使這些代碼發送和接收帶有TCP套接字的圖像,但接收代碼無效,希望您能幫助我 這是發送代碼使用tcp socket發送和接收圖像
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);
以下消息
無法從傳輸連接讀取數據。可以執行套接字操作,因爲系統缺少足夠的緩衝空間或隊列已滿。
就在您嘗試執行行'data = new byte [size];'之前* size *中有什麼值? – 2012-07-31 00:02:45
-1991225785是價值,但當我刪除IPAdress.HostToNetworkOrder它變得積極 – 2012-07-31 00:07:02
看來你會想要相反 - 'IPAddress.NetworkToHostOrder',不是?你從網絡獲取它,並且需要它作爲當前主機上的一個int。 – ceyko 2012-07-31 00:08:42