C#图片传输

如果传送的图片是readonly,可以通过FileInfo.IsReadOnly = false先屏蔽readonly,不然本文代码会出现小错误:

Client Code:

 

using System;

 

using System.Collections.Generic;

 

using System.Text;

 

using System.Net;

 

using System.Net.Sockets;

 

using System.IO;

 

class Program

 

{

static void Main(string[] args)

{

SendImageToServer("image.jpg");

}

static void SendImageToServer(string imgURl)

{

if (!File.Exists(imgURl)) return;

FileStream fs = File.Open(imgURl, FileMode.Open);

byte[] fileBytes = new byte[fs.Length];

using (fs)

{

fs.Read(fileBytes, 0, fileBytes.Length);

fs.Close();

}

IPAddress address = IPAddress.Parse("127.0.0.1");

TcpClient client = new TcpClient();

client.Connect(address, 8000);

using (client)

{

NetworkStream ns = client.GetStream();

using (ns)

{

ns.Write(fileBytes, 0, fileBytes.Length);

}

}

}

}

Server code:

 

using System;

 

using System.Collections.Generic;

 

using System.Text;

 

using System.Net;

 

using System.Net.Sockets;

 

using System.IO;

 

using System.Drawing;

 

using System.Drawing.Imaging;

 

class Program

 

{

static TcpClient client;

static FileStream fs = new FileStream("image.jpg", FileMode.Create);

static int bufferlength = 200;

static byte[] buffer = new byte[bufferlength];

static NetworkStream ns;

static void Main(string[] args)

{

ConnectAndListen();

}

static void ConnectAndListen()

{

TcpListener listener = new TcpListener(IPAddress.Any, 8000);

listener.Start();

while (true)

{

Console.WriteLine("wait for connecting...");

client = listener.AcceptTcpClient();

Console.WriteLine("connected");

ns = client.GetStream();

if (ns.DataAvailable)

{

ns.BeginRead(buffer, 0, bufferlength, ReadAsyncCallBack, null);

}

}

}

static void ReadAsyncCallBack(IAsyncResult result)

{

int readCount;

readCount = client.GetStream().EndRead(result);

if (readCount < 1)

{

client.Close();

ns.Dispose();

fs.Dispose();

return;

}

fs.Write(buffer, 0, readCount);

ns.BeginRead(buffer, 0, 200, ReadAsyncCallBack, null);

}

}

 

你可能感兴趣的:(String,server,C#,null,buffer,byte)