c# c/s结构Socket上传文件的代码
仅需要c# socket上传图片文件的简单代码,最好是两个函数(上传和下载)就可以了,我没接触过这个,我现在只需要实现该功能就可以了,我也不懂的怎么用流来写,希望最好写个实例代码,多谢了 展开
发送端(client)
private void button2_Click(object sender, EventArgs e)
{
this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartSend));
TempThread.Start();
}private void StartSend()
{
//FileInfo EzoneFile = new FileInfo(this.textBox1.Text);string path = @"E:\old F directory\TangWei\kangge\new1.jpg";
FileInfo EzoneFile = new FileInfo(path);
FileStream EzoneStream = EzoneFile.OpenRead();
int PacketSize = 100000;
int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));
// this.textBox8.Text = PacketCount.ToString();
// this.progressBar1.Maximum = PacketCount;
int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));
// this.textBox9.Text = LastDataPacket.ToString();
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipep);
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));
byte[] data = new byte[PacketSize];
for(int i=0; i<PacketCount; i++)
{
EzoneStream.Read(data, 0, data.Length);TransferFiles.SendVarData(client, data);
// this.textBox10.Text = ((int)(i + 1)).ToString();
// this.progressBar1.PerformStep();
}if(LastDataPacket != 0)
{
data = new byte[LastDataPacket];EzoneStream.Read(data, 0, data.Length);
TransferFiles.SendVarData(client,data);
// this.progressBar1.Value = this.progressBar1.Maximum;
}
client.Close();EzoneStream.Close();
this.button2.Enabled = true;
}接收端 (server)
private void button2_Click(object sender, EventArgs e)
{
//int i = 0;
//FileStream recfs = new FileStream("E:\\kangge.jpg", FileMode.OpenOrCreate);
//Byte[] recbyte = new Byte[2000000];
//Socket hostsocket = receive.Accept();
//BinaryWriter newfilestr = new BinaryWriter(recfs);
//hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);
//for (i = 0; i < recbyte.Length; i++)
//{
// newfilestr.Write(recbyte, i, 1);
//}
//recfs.Close();//hostsocket.Shutdown(SocketShutdown.Receive);
//hostsocket.Close();this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
TempThread.Start();
}
private void StartReceive()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
Socket client = server.Accept();
// IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
// string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
// string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
int file_name = 1;string fileaddr = "E:\\old F directory\\TangWei\\Copy of kangge\\" + file_name.ToString() + ".jpg";
FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);// int SendedCount = 0;
while(true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if(data.Length == 0)
{
break;
}
else
{
// SendedCount++;
MyFileStream.Write(data, 0, data.Length);
}
}MyFileStream.Close();
client.Close();
this.button2.Enabled = true;
}公共类。 TransferFiles
class TransferFiles
{public TransferFiles()
{}
public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);//send the size of data array.while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}return total;
}public static byte[] ReceiveVarData(Socket s) // return array that store the received data.
{
int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];while (total < size)
{
recv = s.Receive(data, total, dataleft, SocketFlags.None);
if (recv == 0)
{
data = null;
break;
}
total += recv;
dataleft -= recv;
}return data;
}
}
int port = 1234;
int port = 1234;
IPAddress ip = IPAddress.Parse("127.0.0.1");
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(ip,port);
//socket.Blocking = false;
socket.Bind(iep);
socket.Listen(10);
Console.WriteLine("start......");
try
{
for (int i = 0; i < 10;i++ )
{
}
}
catch
{
Console.WriteLine("异常!");
socket.Close();
}
接收端
private void Receive(Socket socket)
{
NetworkStream ns = new NetworkStream(socket);
FileStream fs = new FileStream("c:\\file.txt", FileMode.OpenOrCreate);
bool isRead = true;
while (isRead)
{
int count = ns.Read(this._receiveBuf, 0, this._receiveBuf.Length);
int datanum = 0;
datanum = BitConverter.ToInt32(this._receiveBuf, 0); //从buffer中的前4个字节读出count
if (datanum > 0) //确定每次要接受多少字节数
{
fs.Write(this._receiveBuf, 4, datanum);
}
else //如果接受字节数为0 就推出
{
isRead = false;
}
}
this.txtFile.Text = "文件传输成功";
fs.Close();
}
---------------------
发送端
private void btSend_Click(object sender, System.EventArgs e)
{
if (this._isConnect)
{
_ns = _tc.GetStream();
string path = this.txtPath.Text.Trim();
FileStream fs = new FileStream(path, FileMode.Open);
int sendCount = 0;
byte[] countbuffer = null;
byte[] clientbuffer = new byte[1004];
while (sendCount < fs.Length && _ns.CanWrite)
{
int count = fs.Read(_sendBuf, 0, _sendBuf.Length); //读出要发送的数据
countbuffer = BitConverter.GetBytes(count);
countbuffer.CopyTo(clientbuffer,0);
_sendBuf.CopyTo(clientbuffer, 4);
this._ns.Write(clientbuffer, 0, 4 + count); //写入网络流
sendCount += count;
}
countbuffer = BitConverter.GetBytes(0); //发送完文件后 发送count = 0
this._ns.Write(countbuffer, 0, countbuffer.Length); //使接收端停止
_ns.Close();
fs.Close();
}
}
http://hi.baidu.com/lqj1112/blog/item/9a0fd21638c6461e962b4336.html
http://topic.csdn.net/u/20080514/23/23e325fc-7040-4c0b-bb6c-d1223704397c.html
Int32 port = 9900;
TcpClient tc = new TcpClient();
tc.Connect(server,port);
String file = @"c:\1.doc";
FileStream fs = File.Open(file,FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bt = new byte[(int)fs.Length];
br.Read(bt, 0, bt.Length);
NetworkStream ns = tc.GetStream();
ns.Write(bt, 0, bt.Length);
byte[] receive = new byte[1024];
ns.Read(receive, 0, receive.Length);
String res = System.Text.Encoding.BigEndianUnicode.GetString(receive);
if (res == "ok")
{
}
else
{
}
tc.Client.Close();
tc.Close();
简单的是这样,发文件好说,关键在于服务器端的解析.